Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading file using fread with row and column names

Tags:

r

csv

data.table

Using fread, how to read CSV file which contains row and column names. I tried following but it is not reading the row and column names properly.

The csv file looks like (where C1,C2,C3 are column names and r1, r2, r3 are row names)

input = ",C1,C2,C3
r1,A,B,C
r2,1,3,5
3,2,4,6"

I use function

require(data.table)
fread(input,header = TRUE)

which give

   r1 A B C
1: r2 1 3 5
2:  3 2 4 6

How can I properly read CSV using fread?

like image 278
d.putto Avatar asked Aug 07 '14 13:08

d.putto


People also ask

Can fread read CSV?

We're able to successfully import the CSV file using the fread() function. Note: We used double backslashes (\\) in the file path to avoid a common import error. Notice that we didn't have to specify the delimiter either since the fread() function automatically detected that it was a comma.

What is the difference between fread and read CSV?

I understand that fread() should be faster than read. csv() because it tries to first read rows into memory as character and then tries to convert them into integer and factor as data types. On the other hand, fread() simply reads everything as character.

Can fread read TSV?

Use `fread()` to read a csv/tsv with row names (e.g. one created with `write.

How do I make certain columns read only in R?

Method 1: Using read. table() function. In this method of only importing the selected columns of the CSV file data, the user needs to call the read. table() function, which is an in-built function of R programming language, and then passes the selected column in its arguments to import particular columns from the data.


1 Answers

You should submit a bug report.

Here is a work-around:

colnames <- strsplit(readLines(textConnection(input), n=1), ",")[[1]]
colnames[1] <- "rownames"
setnames(DT <- fread(input, skip=1, header=FALSE), colnames)
DT
#   rownames C1 C2 C3
#1:       r1  A  B  C
#2:       r2  1  3  5
#3:        3  2  4  6

As you should know, data.table doesn't support rownames.

like image 115
Roland Avatar answered Sep 22 '22 09:09

Roland