df <- data.frame(col1 = rep(1, 15),
col2 = rep(2, 15),
col3 = rep(3, 15),
group = c(rep("A", 5), rep("B", 5), rep("C", 5)))
for(col in c("col1", "col2", "col3")){
filt.df <- df %>%
filter(group == "A") %>%
select(group, col)
# do other things, like ggplotting
}
Run Code Online (Sandbox Code Playgroud)
错误:所有 select() 输入必须解析为整数列位置。以下不要: * col
如何使用 迭代特定的列向量dplyr?我知道我会df[[col]]在baseR 中使用类似的东西,但我不熟悉如何在dplyr.
这应该有效。我使用 select_() 函数
library(dplyr)
df <- data.frame(col1 = rep(1, 15),
col2 = rep(2, 15),
col3 = rep(3, 15),
group = c(rep("A", 5), rep("B", 5), rep("C", 5)))
for(col in c("col1", "col2", "col3")){
filt.df <- df %>%
filter(group == "A") %>%
select_(.dots = c('group', col))
# do other things, like ggplotting
print(filt.df)
}
Run Code Online (Sandbox Code Playgroud)