如何在R中按名称模式删除列? [英] How to drop columns by name pattern in R?
问题描述
我有这个数据框:
state county city region mmatrix X1 X2 X3 A1 A2 A3 B1 B2 B3 C1 C2 C3
1 1 1 1 111010 1 0 0 2 20 200 Push 8 12 NA NA NA
1 2 1 1 111010 1 0 0 4 NA 400 Shove 9 NA
现在我想排除名称以某个字符串结尾的列,比如1"(即 A1 和 B1).我写了这段代码:
Now I want to exclude columns whose names end with a certain string, say "1" (i.e. A1 and B1). I wrote this code:
df_redacted <- df[, -grep("\\1$", colnames(df))]
然而,这似乎删除了每一列.如何修改代码,使其仅删除与模式匹配的列(即以3"或任何其他字符串结尾)?
However, this seems to delete every column. How can I modify the code so that it only deletes the columns that matches the pattern (i.e. ends with "3" or any other string)?
解决方案必须能够处理具有数值和分类值的数据帧.
The solution has to be able to handle a dataframe with has both numerical and categorical values.
推荐答案
我使用 dplyr
/tidyverse
找到了一个简单的答案.如果您的 colnames
包含This",则所有包含This"的变量都将被删除.将被删除.
I found a simple answer using dplyr
/tidyverse
. If your colnames
contain "This", then all variables containing "This" will be dropped.
library(dplyr)
df_new <- df %>% select(-contains("This"))
这篇关于如何在R中按名称模式删除列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!