两个例子对我很有帮助.
我如何选择:1)名称以b或B开头的变量(即不区分大小写)或2)名称包含3的变量
df <- data.frame(a1 = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
a2 = c("A", "D", "A", "C"), a3 = c(8, 3, 9, 9),
b1 = c(1, 1, 1, 2), b2 = c( 5, 4, 3,2), b3 = c(3, 4, 3, 4),
B1 = c(3, 6, 4, 4))
Run Code Online (Sandbox Code Playgroud)
Bri*_*ggs 33
如果您只想要变量名称:
grep("^[Bb]", names(df), value=TRUE)
grep("3", names(df), value=TRUE)
Run Code Online (Sandbox Code Playgroud)
如果您想要选择这些列,那么
df[,grep("^[Bb]", names(df), value=TRUE)]
df[,grep("^[Bb]", names(df))]
Run Code Online (Sandbox Code Playgroud)
第一个使用按名称选择,第二个使用按一组列号选择.
当我喜欢上面的答案时,我也想提供一个“ tidyverse”解决方案。如果您像我经常做的那样做大量的管道并尝试一次做几件事,那么您可能会喜欢这个答案。另外,我发现此代码更具“人性化”可读性。
该函数tidyselect::vars_select将从第一个参数中的字符向量中选择变量,该变量应包含基于选择辅助函数(例如starts_with或)的相应数据框的名称。matches
library(dplyr)
library(tidyselect)
df <- data.frame(a1 = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
a2 = c("A", "D", "A", "C"), a3 = c(8, 3, 9, 9),
b1 = c(1, 1, 1, 2), b2 = c( 5, 4, 3,2), b3 = c(3, 4, 3, 4),
B1 = c(3, 6, 4, 4))
# will select the names starting with a "b" or a "B"
tidyselect::vars_select(names(df), starts_with('b', ignore.case = TRUE))
# use select in conjunction with the previous code
df %>%
select(vars_select(names(df), starts_with('b', ignore.case = TRUE)))
# Alternatively
tidyselect::vars_select(names(df), matches('^[Bb]'))
Run Code Online (Sandbox Code Playgroud)
需要注意的是默认ignore.case的TRUE,但我把它放在这里明确地表明,在未来的情况下,读者都好奇如何调整代码。在include和exclude参数也是非常有用的。例如,vars_select(names(df), matches('^[Bb]'), include = 'a1')如果您想要以“ B”或“ b”开头的所有内容,并且还希望包含“ a1”,则可以使用。