你可以使用R中dplyr包的以下函数来选择不以特定字符串开头的列。
方法1:选择不以一个特定字符串开头的列
df %>%
select(-starts_with("string1"))
方法2:选择不以几个字符串开始的列
df %>%
select(-starts_with(c("string1", "string2", "string3")))
下面的例子展示了如何在R语言中使用这些方法中的每一种,以及如何在下面的数据框架中进行实践:
#create data frame
df <- data.frame(store1_sales=c(12, 10, 14, 19, 22, 25, 29),
store1_returns=c(3, 3, 2, 4, 3, 2, 1),
store2_sales=c(8, 8, 12, 14, 15, 13, 12),
store2_returns=c(1, 2, 2, 1, 2, 1, 3),
promotions=c(0, 1, 1, 1, 0, 0, 1))
#view data frame
df
store1_sales store1_returns store2_sales store2_returns promotions
1 12 3 8 1 0
2 10 3 8 2 1
3 14 2 12 2 1
4 19 4 14 1 1
5 22 3 15 2 0
6 25 2 13 1 0
7 29 1 12 3 1
例子1:选择不以一个特定字符串开头的列
下面的代码显示了如何使用**-starts_with()**函数在数据框中只选择不以 "store1 "开头的列:
library(dplyr)
#select all columns that do not start with "store1"
df %>%
select(-starts_with("store1"))
store2_sales store2_returns promotions
1 8 1 0
2 8 2 1
3 12 2 1
4 14 1 1
5 15 2 0
6 13 1 0
7 12 3 1
注意,以 "store1 "开头的两列没有被返回。
例2:选择不以几个字符串中的一个开头的列
下面的代码显示了如何使用**-starts_with()**函数只选择数据框中不以 "store1 "或 "prom "开头的列:
library(dplyr)
#select all columns that do not start with "store1" or "prom"
df %>%
select(-starts_with(c("store1", "prom")))
store2_sales store2_returns
1 8 1
2 8 2
3 12 2
4 14 1
5 15 2
6 13 1
7 12 3
注意,任何以 "store1 "或 "prom "开头的列都不会被返回。
注意:默认情况下,starts_with()函数是不区分大小写的。要使该函数区分大小写,请在该函数中使用ignore.case=FALSE参数。