【问题标题】:Iterate through columns in dplyr?遍历 dplyr 中的列?
【发布时间】:2017-02-11 12:36:34
【问题描述】:
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
 }

错误:所有 select() 输入必须解析为整数列位置。 以下不: * 列

如何使用dplyr 遍历特定的列向量?我知道我会在base R 中使用df[[col]] 之类的东西,但我不熟悉如何在dplyr 中使用。

【问题讨论】:

  • 所以您想要一个包含 A 组和 col1、A 组和 col2、A 组和 col3、B 组和 col1 等的列表?
  • 是的。在我的真实数据中,col1col2col3 是我想要制作不同图表的差异向量。

标签: r dplyr


【解决方案1】:

这应该可以。我使用 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)
}

【讨论】:

    【解决方案2】:

    select_ 和其他下划线替代品现在在 dplyr 中折旧。现在应该使用select(group, .data[[col]])。有关更多信息,请参阅 dplyr 帮助中的 programming 插图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多