我想从数据帧中删除一些列。我知道我们可以使用如下方法单独删除它们:
df$x <- NULL
但我希望用更少的命令来做到这一点。
另外,我知道我可以像这样使用整数索引删除列:
df <- df[ -c(1, 3:6, 12) ]
但我担心变量的相对位置可能会改变。
考虑到R的强大功能,我认为可能有一种比逐个删除每一列更好的方法。
我想从数据帧中删除一些列。我知道我们可以使用如下方法单独删除它们:
df$x <- NULL
但我希望用更少的命令来做到这一点。
另外,我知道我可以像这样使用整数索引删除列:
df <- df[ -c(1, 3:6, 12) ]
但我担心变量的相对位置可能会改变。
考虑到R的强大功能,我认为可能有一种比逐个删除每一列更好的方法。
当前回答
基于grep()将返回数字向量这一事实,有一种可能更强大的策略。如果你有一个很长的变量列表,就像我在我的数据集中做的那样,一些变量以“。A和其他以。结尾的。B"你只想要以。结尾的。A”(连同所有不符合任何一种模式的变量,这样做:
dfrm2 <- dfrm[ , -grep("\\.B$", names(dfrm)) ]
对于手头的情况,使用Joris Meys的例子,它可能没有那么紧凑,但它将是:
DF <- DF[, -grep( paste("^",drops,"$", sep="", collapse="|"), names(DF) )]
其他回答
在数据帧中按列名删除和删除列。
A <- df[ , c("Name","Name1","Name2","Name3")]
还有一个子集命令,如果你知道你想要哪些列,它很有用:
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[, !(colnames(df) %in% c("x","bar","foo"))]
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")]
除了在前面的回答中演示的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'))