R data.table - new column with ':=' and keep existing column

为君一笑 提交于 2021-01-28 11:44:04

问题


Is it possible to create a new column and keep (few) existing columns in the statement ? e.g. creation of "x" column and then keeping "x" and "mpg" column

dt <- data.table(mtcars)

dt[,x:=mpg]

dt[,.(x,mpg)]

回答1:


If you want to do the replacement by reference, using := then you can do

dt[, x:=mpg][, setdiff(colnames(dt), c('x', 'mpg')) := NULL]



回答2:


If we need it in a single step, instead of doing the := to modify the original dataset, specify it with = inside list or .(

dt[,.(x = mpg, mpg)]

Or if it necessary to create the column in original dataset, it can be piped

dt[, x := mpg][, .(x, mpg)]

If we want to update the columns in the original object, another option is set

set(dt[, x:= mpg], i = NULL, j = names(dt)[!names(dt) %in% c('x', 'mpg')], value = NULL)


来源:https://stackoverflow.com/questions/59922704/r-data-table-new-column-with-and-keep-existing-column

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