如何将逗号分隔的数据加载到R中?

如何将逗号分隔的数据加载到R中?

问题描述:

我有一个像这样的平面文件:

I have a flat file like this:

   x1,   x2,   x3,   x4,   x5
0.438,0.498,3.625,3.645,5.000
2.918,5.000,2.351,2.332,2.643
1.698,1.687,1.698,1.717,1.744
0.593,0.502,0.493,0.504,0.445
0.431,0.444,0.440,0.429,1.0
0.438,0.498,3.625,3.648,5.000

如何在R中加载它.

我试图做到这一点

> x <- read.table("C:\\flatFile.txt", header=TRUE)

但是执行一些操作后,我得到了类似的错误

but after I do some operation I get error like

> colSums(x)
Error in colSums(x) : 'x' must be numeric

如果查看read.table的帮助,您会发现一些本质上为read.table且具有不同默认值的额外功能.如果您倾向于读取大量文件,最好使用这些默认值来读取文件,则为了简洁起见,请使用它们代替read.table.

If you look at the help on read.table you'll discover some extra functions that are essentially read.table with different defaults. If you tend to read in lots of files that would be best read in using those defaults then use them instead of read.table for conciseness.

此代码将读取到您的文件中

This code will read in your file

x <- read.table("C:\\flatFile.txt", header=TRUE, sep = ',')

或此代码

x <- read.csv("C:\\flatFile.txt")

请注意,尽管您可以像read.table一样设置这些基于read.table的命令的任何功能,但是使用它们并重申默认设置是毫无意义的.例如,如果以后还要一直设置header = TRUE和/或sep = ',',请不要理会read.csv.在这种情况下,您最好也使用read.table.

Note that, while you can set any of the features of these read.table based commands just like read.table, it is rather pointless to use them and reiterate the default settings. For example, don't bother with read.csv if you're then going to also be setting header = TRUE, and/or, sep = ',' all of the time as well. You might as well just use read.table in that case.