遍历dplyr中的列? [英] Iterate through columns in dplyr?

查看:65
本文介绍了遍历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(group, col)
     # do other things, like ggplotting
 }




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

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

如何使用<来遍历特定列向量code> dplyr ?我知道我会在 base R中使用类似 df [[col]] 的方法,但不熟悉该怎么做在 dplyr 中。

How can I iterate through a specific vector of columns using dplyr? I know I would use something like df[[col]] in base R, but am unfamiliar with how to do it in dplyr.

推荐答案

这应该可行。我使用select_()函数

this should work. I use the select_() function

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)
}

这篇关于遍历dplyr中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆