R:如何删除data.table中的列?

Mar*_*kes 5 r data.table

关于R包data.table的问题:如何以高效内存的方式删除多个data.table列?

假设要删除的列名存储在vector deleteCol中.

In a data.frame, it is:
DF <- DF[deleteCol] <- list()
Run Code Online (Sandbox Code Playgroud)

对于data.table,我试过:

DT[, deleteCol, with=FALSE] <- list()
Run Code Online (Sandbox Code Playgroud)

但这给了 unused argument(s) (with = FALSE)

use*_*1_G 5

好的,这里有几个选择.最后一个看起来正是你想要的......

 x<-1:5
 y<-1:5
 z<-1:5
 xy<-data.table(x,y,z)
 NEWxy<-subset(xy, select = -c(x,y) ) #removes column x and y
Run Code Online (Sandbox Code Playgroud)

id<-c("x","y")
newxy<-xy[, id, with=FALSE]
newxy #gives just x and y e.g.

   #  x y
#[1,] 1 1
#[2,] 2 2
#[3,] 3 3
#[4,] 4 4
#[5,] 5 5
Run Code Online (Sandbox Code Playgroud)

最后你真正想要的是什么:

anotherxy<-xy[,id:=NULL,with=FALSE] # removes comuns x and y that are in id

#     z
#[1,] 1
#[2,] 2
#[3,] 3
#[4,] 4
#[5,] 5
Run Code Online (Sandbox Code Playgroud)

  • +1.不需要`anotherxy <-`.`:=`通过引用修改`xy`.如果你想要一个修改过的副本,那么你必须明确地复制(); 例如,`anotherxy < - copy(xy)[,id:= NULL,with = FALSE]`. (4认同)