我想从数据帧中删除一些列。我知道我们可以使用如下方法单独删除它们:
df$x <- NULL
但我希望用更少的命令来做到这一点。
另外,我知道我可以像这样使用整数索引删除列:
df <- df[ -c(1, 3:6, 12) ]
但我担心变量的相对位置可能会改变。
考虑到R的强大功能,我认为可能有一种比逐个删除每一列更好的方法。
我想从数据帧中删除一些列。我知道我们可以使用如下方法单独删除它们:
df$x <- NULL
但我希望用更少的命令来做到这一点。
另外,我知道我可以像这样使用整数索引删除列:
df <- df[ -c(1, 3:6, 12) ]
但我担心变量的相对位置可能会改变。
考虑到R的强大功能,我认为可能有一种比逐个删除每一列更好的方法。
当前回答
使用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
其他回答
within(df, rm(x))
可能是最简单的,或者对于多个变量:
within(df, rm(x, y))
或者如果你在处理数据。如何在data.table中按名称删除列?
dt[, x := NULL] # Deletes column x by reference instantly.
dt[, !"x"] # Selects all but x into a new data.table.
或者对于多个变量
dt[, c("x","y") := NULL]
dt[, !c("x", "y")]
df <- data.frame(
+ a=1:5,
+ b=6:10,
+ c=rep(22,5),
+ d=round(runif(5)*100, 2),
+ e=round(runif(5)*100, 2),
+ f=round(runif(5)*100, 2),
+ g=round(runif(5)*100, 2),
+ h=round(runif(5)*100, 2)
+ )
> df
a b c d e f g h
1 1 6 22 76.31 39.96 66.62 72.75 73.14
2 2 7 22 53.41 94.85 96.02 97.31 85.32
3 3 8 22 98.29 38.95 12.61 29.67 88.45
4 4 9 22 20.04 53.53 83.07 77.50 94.99
5 5 10 22 5.67 0.42 15.07 59.75 31.21
> # remove cols: d g h
> newDf <- df[, c(1:3, 5), drop=TRUE]
> newDf
a b c e
1 1 6 22 39.96
2 2 7 22 94.85
3 3 8 22 38.95
4 4 9 22 53.53
5 5 10 22 0.42
你有很多方法可以……
选项1:
df[ , -which(names(df) %in% c("name1","name2"))]
选项2:
df[!names(df) %in% c("name1", "name2")]
选项3:
subset(df, select=-c(name1,name2))
另一种可能性:
df <- df[, setdiff(names(df), c("a", "c"))]
or
df <- df[, grep('^(a|c)$', names(df), invert=TRUE)]
Dplyr解决方案
我怀疑这在这里会得到很多关注,但如果你有一个列列表,你想要删除,并且你想在dplyr链中做它,我在select子句中使用one_of():
这里有一个简单的,可复制的例子:
undesired <- c('mpg', 'cyl', 'hp')
mtcars <- mtcars %>%
select(-one_of(undesired))
可以通过运行?one_of或在这里找到文档:
http://genomicsclass.github.io/book/pages/dplyr_tutorial.html