[英]removing vectors from data frame by suffix in r
数据框中的have
向量包含后缀_rc_1
。 我想从数据框中删除这些向量。 我已经尝试了几个选项,但得到的错误表明我误解了一些东西。 例如:
library(dplyr)
newdata <- subset(mydata, -contains("_rc_1"))
Error: No tidyselect variables were registered
我不知道我如何解决这个问题。
也许这最好用grepl()
和正则表达式来完成,但我正在努力实现一个在这里也能按计划执行的版本。
contains
work with dplyr
If we need to use subset
(a base R
function), use grep
which can take regex pattern and return either a numeric index or the column names itself as select
argument in subset
can take both as valid inputs
subset(mydata, select = grep("_rc_1", names(mydata), value = TRUE, invert = TRUE))
此外,在base R
中有用于前缀/后缀匹配的startsWith/endsWith
subset(mydata, select = names(mydata)[!endsWith(names(mydata), "_rc_1")])
在dplyr
中, select_helpers
- contains
与select
一起使用
library(dplyr)
mydata %>%
select(-contains("_rc_1"))
可使用内置数据集“iris”重现
data(iris)
head(subset(iris, select = names(iris)[!endsWith(names(iris), "Length")]))
iris %>%
select(-contains('Sepal')) %>%
head
在基础 R 中,您可以使用grepl
获取长度等于 ncol ncol(mydata)
的逻辑向量,对于以_rc_1
结尾的列名,该向量为TRUE
($ 确保 _rc_1 出现在末尾)。 然后将TRUE
和FALSE
交换为!
,您可以使用[]
对数据框进行子集化。
newdata <- mydata[!grepl('_rc_1$', names(mydata))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.