How do you delete a column by name in data.table?

前端 未结 8 1016
北海茫月
北海茫月 2020-12-02 03:52

To get rid of a column named \"foo\" in a data.frame, I can do:

df <- df[-grep(\'foo\', colnames(df))]

However, once df

相关标签:
8条回答
  • 2020-12-02 04:42

    I simply do it in the data frame kind of way:

    DT$col = NULL
    

    Works fast and as far as I could see doesn't cause any problems.

    UPDATE: not the best method if your DT is very large, as using the $<- operator will lead to object copying. So better use:

    DT[, col:=NULL]
    
    0 讨论(0)
  • 2020-12-02 04:46

    You can also use set for this, which avoids the overhead of [.data.table in loops:

    dt <- data.table( a=letters, b=LETTERS, c=seq(26), d=letters, e=letters )
    set( dt, j=c(1L,3L,5L), value=NULL )
    > dt[1:5]
       b d
    1: A a
    2: B b
    3: C c
    4: D d
    5: E e
    

    If you want to do it by column name, which(colnames(dt) %in% c("a","c","e")) should work for j.

    0 讨论(0)
提交回复
热议问题