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

df$x <- NULL

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

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

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

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

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


当前回答

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

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))

其他回答

如果你不想使用@hadley's上面的另一个解决方案:如果"COLUMN_NAME"是你想删除的列的名称:

df[,-which(names(df) == "COLUMN_NAME")]

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

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))

在数据帧中按列名删除和删除列。

A <- df[ , c("Name","Name1","Name2","Name3")]

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

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(
  x=1:10,
  y=10:1,
  z=rep(5,10),
  a=11:20
)
DF

输出:

    x  y z  a
1   1 10 5 11
2   2  9 5 12
3   3  8 5 13
4   4  7 5 14
5   5  6 5 15
6   6  5 5 16
7   7  4 5 17
8   8  3 5 18
9   9  2 5 19
10 10  1 5 20

DF[c("a","x")] <- list(NULL)

输出:

        y z
    1  10 5
    2   9 5
    3   8 5
    4   7 5
    5   6 5
    6   5 5
    7   4 5
    8   3 5    
    9   2 5
    10  1 5