2017-09-27 56 views
0

列索引组我遇到的情况,我在一个变量得到列索引和我有GROUP BY和变量如何通过在dplyr

col_index <- which(sapply(dataframe, function(x) any(x == "Area of Maintenance"))) 

> col_index 
    X__7 
    8 

现在我的希望将总结col_index值如下

df%>% 
group_by(df[col_index]) %>% 
summarise(count = n()) %>% 
as.data.frame() 

它给我下面的错误。

Error in mutate_impl(.data, dots) : 
Evaluation error: Column index must be at most 1 if positive, not 8. 

col_index具有动态值。我该怎么做r?

+3

的帮助试试'group_by_at(col_index)'。 – mt1022

回答

2

您可以通过搭配使用group_by_if给定函数的所有列组:

df %>% 
    group_by_if(function(x) any(x == "Area of Maintenance")) %>% 
    summarise(count = n()) %>% 
    as.data.frame() 
+0

感谢您的回答,但如果我想用'col_index'来做这件事呢?我们可以这样做吗? – Neil