我想读取一个CSV文件,其第一行是变量名,后续行是这些变量的内容.有些变量是数字的,有些是文本,有些甚至是空的.
file = "path/file.csv"
f = file(file,'r')
varnames = strsplit(readLines(f,1),",")[[1]]
data = strsplit(readLines(f,1),",")[[1]]
Run Code Online (Sandbox Code Playgroud)
既然数据包含所有变量,我该如何使数据能够识别正在读取的数据类型,就像我一样read.csv.
我需要逐行读取数据(或一次读取n行),因为整个数据集太大而无法读入R.
Gre*_*reg 11
根据DWin的评论,您可以尝试这样的事情:
read.clump <- function(file, lines, clump){
if(clump > 1){
header <- read.csv(file, nrows=1, header=FALSE)
p = read.csv(file, skip = lines*(clump-1),
#p = read.csv(file, skip = (lines*(clump-1))+1 if not a textConnection
nrows = lines, header=FALSE)
names(p) = header
} else {
p = read.csv(file, skip = lines*(clump-1), nrows = lines)
}
return(p)
}
Run Code Online (Sandbox Code Playgroud)
您可能也应该为函数添加一些错误处理/检查.
然后用
x = "letter1, letter2
a, b
c, d
e, f
g, h
i, j
k, l"
>read.clump(textConnection(x), lines = 2, clump = 1)
letter1 letter2
1 a b
2 c d
> read.clump(textConnection(x), lines = 2, clump = 2)
letter1 letter2
1 e f
2 g h
> read.clump(textConnection(x), lines = 3, clump = 1)
letter1 letter2
1 a b
2 c d
3 e f
> read.clump(textConnection(x), lines = 3, clump = 2)
letter1 letter2
1 g h
2 i j
3 k l
Run Code Online (Sandbox Code Playgroud)
现在你只需要*应用于团块
此处讨论的另一种策略是处理非常大的(例如,> 1e7ish单元格)CSV文件:
read.csv.sql从sqldf包中导入数据库中的数据.这样做的主要优点是它通常更快,您可以轻松过滤内容,只包含您需要的列或行.
了解如何使用RSqlite将CSV导入sqlite?了解更多信息.
| 归档时间: |
|
| 查看次数: |
15247 次 |
| 最近记录: |