如何 select R 中带有星号的变量

How to select variables with star symbols in R

我想 select 我在 R 中的 csv 文件中的一些变量。我使用了这个 select(gender*, age*),但出现错误 - 找不到对象。我尝试了 select(`gender*`, `age*`)select(starts_with(gender), starts_with(age)),但都不起作用。有谁知道如何 select 带星号的变量?非常感谢!

dplyr 中的 select 可能被任何其他包中的 select 掩盖了,因为它工作正常。使用 :: 指定包名,或者在新的 R 会话中执行此操作,仅加载 dplyr

library(dplyr)
data(iris)
iris$'gender*' <- 'M'
iris%>% 
      head %>% 
      dplyr::select(`gender*`)
#   gender*
#1       M
#2       M
#3       M
#4       M
#5       M
#6       M

要select以特定字符串开头的列名列表,可以使用dplyr中的starts_with()函数。为了说明,我们将 select 以字符串 Sepal 开头的两列,如 Sepal.LengthSepal.Width

library(dplyr)
select(iris,starts_with("Sepal")) %>% head()

...输出:

> select(iris,starts_with("Sepal")) %>% head()
  Sepal.Length Sepal.Width
1          5.1         3.5
2          4.9         3.0
3          4.7         3.2
4          4.6         3.1
5          5.0         3.6
6          5.4         3.9
>

我们可以在 Base R 中用 grepl() 和一个正则表达式做同样的事情。

# base R version
head(iris[,grepl("^Sepal",names(iris))])

...输出:

> head(iris[,grepl("^Sepal",names(iris))])
  Sepal.Length Sepal.Width
1          5.1         3.5
2          4.9         3.0
3          4.7         3.2
4          4.6         3.1
5          5.0         3.6
6          5.4         3.9
>

另请注意,如果使用 read.csv() 在 R 中创建数据框,它会将列标题中出现的任何 * 转换为 .

# confirm that * is converted to . in read.csv()
textFile <- 'v*1,v*2
1,2
3,4
5,6'
data <- read.csv(text = textFile,header = TRUE)
# see how illegal column name * is converted to . 
names(data)

...以及输出:

> names(data)
[1] "v.1" "v.2"
>