fread from data.table package when column names include spaces and special characters?

情到浓时终转凉″ 提交于 2019-12-01 03:26:58
42-

It should be rather difficult to get a leading space in a column name. Should not happen by "casual coding". On the other hand I don't see very much error checking in the fread code, so maybe until this undesirable behavior is fixed, (or the feature request refused), you can do something like this:

setnames(DT, make.names(colnames(DT))) 

If on the other hand you are bothered by the fact that colnames(DT) will display the column names with quotes then just "get over it." That's how the interactive console will display any character value.

If you have a data item in a character column that looks like " ttt" in the original, then it's going to have leading spaces when imported, and you need to process it with colnames(dfrm) <- sub("^\\s+", "", colnames(dfrm)) or one of the several trim functions in various packages (such as 'gdata')

A little bit modified BondedDust version, because setnames function is not used with <- sign:

setnames(DT, make.names(colnames(DT))

You can use argument check.names=T in fread function of data.table

p2p <- fread("p2p.csv", header = TRUE, stringsAsFactors=FALSE, check.names=T)

It uses make.names function in background

default is FALSE. If TRUE then the names of the variables in the data.table 
are checked to ensure that they are syntactically valid variable names. If 
necessary they are adjusted (by make.names) so that they are, and also to 
ensure that there are no duplicates.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!