del <- c('a','b')DT <- data.table(a=1:10, b=1:10, c=1:10, d=1:10)DT[, (del) := NULL]DT <- <- data.table(a=1:10, b=1:10, c=1:10, d=1:10)DT[, {del} := NULL]# force or `c` would also work.
您也可以使用set,这避免了[.data.table、也为#2工作!的开销
df <- data.frame(a=1:10, b=1:10, c=1:10, d=1:10)DT <- data.table(df)
# drop `a` from df (no copying involved)
set(df, j = 'a', value = NULL)# drop `b` from DT (no copying involved)set(DT, j = 'b', value = NULL)
library(dplyr)starwars %>%select(-(name:mass)) %>% # the range of columns from 'name' to 'mass'select(-contains('color')) %>% # any column name that contains 'color'select(-starts_with('bi')) %>% # any column name that starts with 'bi'select(-ends_with('er')) %>% # any column name that ends with 'er'select(-matches('^f.+s$')) %>% # any column name matching the regex patternselect_if(~!is.list(.)) %>% # not by column name but by data typehead(2)
# A tibble: 2 x 2homeworld species<chr> <chr>1 Tatooine Human2 Tatooine Droid
DF <- data.frame(one=c('a','b'), two=c('c', 'd'), three=c('e', 'f'), four=c('g', 'h'))DF# one two three four#1 a d f i#2 b e g j
DF[which(names(DF) %in% c('two','three')) *-1]# one four#1 a g#2 b h