我想从数据帧中删除一些列。我知道我们可以使用如下方法单独删除它们:

df$x <- NULL

但我希望用更少的命令来做到这一点。

另外,我知道我可以像这样使用整数索引删除列:

df <- df[ -c(1, 3:6, 12) ]

但我担心变量的相对位置可能会改变。

考虑到R的强大功能,我认为可能有一种比逐个删除每一列更好的方法。


当前回答

提供数据帧和一串逗号分隔的名称来删除:

remove_features <- function(df, features) {
  rem_vec <- unlist(strsplit(features, ', '))
  res <- df[,!(names(df) %in% rem_vec)]
  return(res)
}

用法:

remove_features(iris, "Sepal.Length, Petal.Width")

其他回答

还有一个子集命令,如果你知道你想要哪些列,它很有用:

df <- data.frame(a = 1:10, b = 2:11, c = 3:12)
df <- subset(df, select = c(a, c))

要删除列a,c,你可以这样做:

df <- subset(df, select = -c(a, c))

我一直在想一定有更好的习语,但对于按名称减法的列,我倾向于这样做:

df <- data.frame(a=1:10, b=1:10, c=1:10, d=1:10)

# return everything except a and c
df <- df[,-match(c("a","c"),names(df))]
df

如果您希望通过引用删除列并避免与data.frames相关的内部复制,则可以使用数据。表包和函数:=

您可以将字符向量名称传递到:=运算符的左侧,并将NULL作为RHS。

library(data.table)

df <- data.frame(a=1:10, b=1:10, c=1:10, d=1:10)
DT <- data.table(df)
# or more simply  DT <- data.table(a=1:10, b=1:10, c=1:10, d=1:10) #

DT[, c('a','b') := NULL]

如果希望将名称预定义为[调用之外的字符向量,请将对象名称包装在()或{}中,以强制LHS在调用范围内计算,而不是作为DT范围内的名称。

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]的开销。表,也适用于data.frames!

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)

提供数据帧和一串逗号分隔的名称来删除:

remove_features <- function(df, features) {
  rem_vec <- unlist(strsplit(features, ', '))
  res <- df[,!(names(df) %in% rem_vec)]
  return(res)
}

用法:

remove_features(iris, "Sepal.Length, Petal.Width")

使用which找到要删除的列的索引。给这些下标一个负号(*-1)。然后对这些值进行子集化,这将从数据框架中删除它们。这是一个例子。

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