我想从数据帧中删除一些列。我知道我们可以使用如下方法单独删除它们:
df$x <- NULL
但我希望用更少的命令来做到这一点。
另外,我知道我可以像这样使用整数索引删除列:
df <- df[ -c(1, 3:6, 12) ]
但我担心变量的相对位置可能会改变。
考虑到R的强大功能,我认为可能有一种比逐个删除每一列更好的方法。
我想从数据帧中删除一些列。我知道我们可以使用如下方法单独删除它们:
df$x <- NULL
但我希望用更少的命令来做到这一点。
另外,我知道我可以像这样使用整数索引删除列:
df <- df[ -c(1, 3:6, 12) ]
但我担心变量的相对位置可能会改变。
考虑到R的强大功能,我认为可能有一种比逐个删除每一列更好的方法。
当前回答
除了在前面的回答中演示的select(-one_of(drop_col_names))之外,还有其他一些dplyr选项可以使用select()删除列,这些选项不涉及定义所有特定的列名(使用dplyr starwars示例数据来获取列名中的某些种类):
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 pattern
select_if(~!is.list(.)) %>% # not by column name but by data type
head(2)
# A tibble: 2 x 2
homeworld species
<chr> <chr>
1 Tatooine Human
2 Tatooine Droid
如果您需要删除数据帧中可能存在也可能不存在的列,这里使用select_if()略有变化,与使用one_of()不同,它不会抛出Unknown列:如果列名不存在,则会发出警告。在这个例子中,'bad_column'不是数据帧中的列:
starwars %>%
select_if(!names(.) %in% c('height', 'mass', 'bad_column'))
其他回答
你有很多方法可以……
选项1:
df[ , -which(names(df) %in% c("name1","name2"))]
选项2:
df[!names(df) %in% c("name1", "name2")]
选项3:
subset(df, select=-c(name1,name2))
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
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
基于grep()将返回数字向量这一事实,有一种可能更强大的策略。如果你有一个很长的变量列表,就像我在我的数据集中做的那样,一些变量以“。A和其他以。结尾的。B"你只想要以。结尾的。A”(连同所有不符合任何一种模式的变量,这样做:
dfrm2 <- dfrm[ , -grep("\\.B$", names(dfrm)) ]
对于手头的情况,使用Joris Meys的例子,它可能没有那么紧凑,但它将是:
DF <- DF[, -grep( paste("^",drops,"$", sep="", collapse="|"), names(DF) )]
我一直在想一定有更好的习语,但对于按名称减法的列,我倾向于这样做:
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