% select(group, col) # do other things, like ggplotting -6ren">
gpt4 book ai didi

r - 遍历 dplyr 中的列?

转载 作者:行者123 更新时间:2023-12-02 15:16:42 24 4
gpt4 key购买 nike

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
}

Error: All select() inputs must resolve to integer column positions. The following do not: * col

如何使用 dplyr 遍历特定的列向量?我知道我会在 base R 中使用类似 df[[col]] 的东西,但我不熟悉如何在 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)
}

关于r - 遍历 dplyr 中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39833762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com