问题
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