fread data.table in R doesn't read in column names

浪尽此生 提交于 2019-12-12 15:22:42

问题


When reading in a data file into R, I can read it in either as a data.frame or a data.table using the data.table package. I would prefer to use data.table in the future since it deals with large data better. However, there are issues with both methods (read.table for data.frames, fread for data.tables) and I'm wondering if there's a simple fix out there.

When I use read.table to produce a data.frame, if my column names include colons or spaces, they are replaced by periods, which I do not want. I want the column names to be read in "as is."

Alternatively, when I use fread to produce a data.table, my column names are not read in at all, which is obviously not desired.

Check out this gist below for a reproducible example:

https://gist.github.com/jeffbruce/b966d41eedc2662bbd4a

Cheers


回答1:


R always try to convert column names to ensure that they are valid variable names, hence it adds periods in place of spaces and colons. If you dont want that you can use check.names=FALSE while using read.table

df1<-read.table("data.txt",check.names = FALSE)

sample(colnames(df1),10)
 [1] "simple lobule white matter"                       
 [2] "anterior lobule white matter"                     
 [3] "hippocampus"                                      
 [4] "lateral olfactory tract"                          
 [5] "lobules 1-2: lingula and central lobule (ventral)"
 [6] "Medial parietal association cortex"               
 [7] "Primary somatosensory cortex: trunk region"       
 [8] "midbrain"                                         
 [9] "Secondary auditory cortex: ventral area"          
[10] "Primary somatosensory cortex: forelimb region"  

you can see that colnames are kept as it is.




回答2:


Here's a solution that might work. I'm not sure if it's the shortest solution or you can do it by clever use of drop in data table, but the hack below does work. The "problem" is the row numbers in your file.

Read in the header file first and then add it to the data table after

header <- read.table("yourfile.csv", header = TRUE, nrow = 1)
indata <- fread("yourfile.csv", skip=1, header=FALSE)
setnames(indata, colnames(header))


来源:https://stackoverflow.com/questions/32767351/fread-data-table-in-r-doesnt-read-in-column-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!