如何阅读R中的单行CSV?

时间:2016-01-22 08:27:38

标签: r csv

我最近一直在研究一个虚拟数据集,我发现提供给我的数据都是单行的。一个类似的例子描述如下:

Name,Age,Gender,Occupation A,10,M,Student B,11,M,Student C,11,F,Student

我想导入数据并获得如下输出:

Name  Age  Gender  Occupation
 A    10     M       Student
 B    11     M       Student
 C    12     F       Student

可能会出现可能缺少值的情况。导入此类数据需要逻辑。任何人都可以帮我建立导入此类数据集的逻辑。

我尝试了正常的导入,但它确实没有帮助。刚刚通过read.csv()函数导入了文件,它没有给我预期的结果。

编辑:如果数据如下:

Name,Age,Gender,Occupation ABC XYZ,10,M,Student B,11,M,Student C,11,F,Student

我希望输出如下:

  Name     Age  Gender  Occupation
 ABC XYZ    10     M       Student
   B        11     M       Student
   C        12     F       Student

2 个答案:

答案 0 :(得分:11)

您可以使用readLines阅读文件,将空格转换为换行符,然后使用read.csv阅读:

# txt <- readLines("my_data.txt") # with a real data file
txt <- readLines(textConnection("Name,Age,Gender,Occupation A,10,M,Student B,11,M,Student C,11,F,Student"))

read.csv(text=gsub(" ","\n",txt))

输出

  Name Age Gender Occupation
1    A  10      M    Student
2    B  11      M    Student
3    C  11      F    Student

答案 1 :(得分:9)

如果您有数百万条记录,您可能希望加快此过程,因此我建议您使用<?php if(Auth()->User()) dd(Auth()->User()->GetFriendsCount()); else dd('not connect'); 的{​​{1}}代替data.table,这也可以使用shell命令在读入R之前预处理文件,fread将比在R中进行字符串操作快得多。

例如,如果您将此CSV存储在read.csv,则可以尝试以下操作:

sed