Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load comma separated data into R?

Tags:

r

load

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

How do I load it in R.

I have tried to do this

> 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
like image 987
edgarmtze Avatar asked Sep 17 '11 00:09

edgarmtze


People also ask

How do I read a comma separated file in R?

The read. table() function in R reads a file into a data frame. The file can be comma-delimited, tab-delimited, or any other delimiter given by the sep= argument. If the argument header= is set to TRUE , the first row is used as the column name.

What is the R command for loading a comma separated value vector file?

csv() as a function to load a comma separated value file. This function is included as part of base R, and performs a similar job to read_csv() . We will be using read_csv() in this course; it is part of the tidyverse, so works well with other parts of the tidyverse, is faster than read.

Can you use csv in R?

While there are R packages designed to access data from Excel spreadsheets (e.g., gdata, RODBC, XLConnect, xlsx, RExcel), users often find it easier to save their spreadsheets in comma-separated values files (CSV) and then use R's built in functionality to read and manipulate the data.


1 Answers

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 = ',')

or this code

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

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.

like image 175
John Avatar answered Oct 19 '22 02:10

John