R data.table multi column coversion by names [duplicate]

让人想犯罪 __ 提交于 2019-12-02 06:53:33
David Arenburg

Yes, the most efficient would be probably to run set in a for loop

Set the desired columns to modify (you can chose all the names too using names(DT) instead)

cols <- c("V1", "V2", "V3") 

Then just run the loop

for (j in cols) set(DT, i = NULL, j = j, value = as.numeric(DT[[j]]))

Or a bit less efficient but more readable way would be just (note the parenthesis around cols which evaluating the variable)

## if you chose all the names in DT, you don't need to specify the `.SDcols` parameter
DT[, (cols) := lapply(.SD, as.numeric), .SDcols = cols] 

Both should be efficient even for a big data set. You can read some more about data.table basics here


Though beware of converting factors to numeric classes in such a way, see here for more details

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