【发布时间】:2013-11-04 04:43:00
【问题描述】:
假设您有一个 CSV 文件。文件的每一行都有数字、向量和日期。每个向量的元素用分号分隔。例如,这个 csv 文件中的向量 y 看起来像“;1;2;4;7;2”。向量的长度不同。我无法使用
读取此文件read.table()
或
read.csv()
即使尝试一些类似于这里写的东西How to read a .csv file containing apostrophes into R?。下面是 CSV 文件中 3 行的简化版本
1,6,;2;3.1;45;31.2;3,2,;1;1;1;1;1;5,10/22/1938 1:25
2,5,;1;22;12;1.4;66,7,;2;3;4;5;6;7;8;6;9,11/25/1938 1:25
3,1,;1;2;3;4;5;6;7;8;9,3.2,;1;2;3;4;5;6;7;9;10;11,11/25/1958 1:25
这里是逗号之间的空格,使其更具可读性
1, 6, ;2;3.1;45;31.2;3, 2, ;1;1;1;1;1;5, 10/22/1938 1:25
2, 5, ;1;22;12;1.4;66, 7, ;2;3;4;5;6;7;8;6;9, 11/25/1938 1:25
3, 1, ;1;2;3;4;5;6;7;8;9, 3.2, ;1;2;3;4;5;6;7;9;10;11, 11/25/1958 1:25
每一行都有相同数量的',',行之间唯一的主要区别是向量可以不同。请注意,有时字段可能为空白。我认为以列表的列表形式输出是最有意义的。我正在考虑编写我自己的函数,它实际上看起来像(我对列表还不是很精通,所以我的语言可能离这里很远)
data <- empty list of a list
while (we haven't reached the end of the file){ #don't know the function to do this
temp = get first line of file #don't know the function to do this
if temp is not empty{ #don't know the function to do this
indices = which(temp==',')
indices.col = which(temp==';')
put temp[1:(indices(1)-1)] in the (counter,1) location of data;
put temp[(indices(1)+1):(indices(2)-1)] in the (counter,2) location of data;
store the vector and deal with the colons somehow in (counter,3) location of data;
}
}
是否有更简单的方法可以做到这一点,也许以我错过的方式使用 read.table。我不打算使用列表列表来做到这一点。我想基本上做一些形式为y = mx + b的回归分析,其中x是数字条目之一,y是应用于向量条目之一的函数的标量输出(例如sum(vector)= a *行 + b) 的第一个条目。所以也许请记住这一点。另请注意,可以选择让此文件使用除分号之外的其他字符来分隔向量。
【问题讨论】: