Is it possible to create a new column and keep (few) existing columns in the statement ? eg creation of "x" column and then keeping "x" and "mpg" column
dt <- data.table(mtcars)
dt[,x:=mpg]
dt[,.(x,mpg)]
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)
如果你想通过引用进行替换,使用:=
那么你可以做
dt[, x:=mpg][, setdiff(colnames(dt), c('x', 'mpg')) := NULL]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.