How to load comma separated data in R?

I have a flat file:

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 

How to load it into R.

I tried to do it

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

but after doing some operation I get an error like

 > colSums(x) Error in colSums(x) : 'x' must be numeric 
+4
source share
2 answers

If you look at help on read.table , you will find some additional functions that are essentially read.table with different default values. If you tend to read the many files that read best when using these defaults, then use them instead of read.table for brevity.

This code will be read in your file

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

or this code

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

Please note that although you can set any of the functions of these commands based on read.table in the same way as read.table , it read.table no sense to use them and repeat the default settings. For example, don't bother with read.csv if you are also going to set header = TRUE and / or, sep = ',' all the time too. In this case, you can just use read.table .

+9
source

You need to use the colClasses option for read.csv. Like this:

 x <- read.csv("C:\\flatFile.txt", head=TRUE, colClasses=c("numeric","numeric","numeric","numeric")) 
0
source

All Articles