pass grouping variables to NSE group_by

23 views
Skip to first unread message

ArjunaCap

unread,
Nov 16, 2016, 2:23:59 PM11/16/16
to manipulatr
I want to pass the results of an ordered factor to group_by_(), but I'm struggling with how to do it.

For example


 library
(dplyr)
 library
(lubridate)
 
 
# given
 my_groups
<- ordered(c("year", "month", "day"))
 
 test_df
<- data.frame(dates = Sys.Date() + days(1:180), ints = 1:180) %>% mutate(year = year(dates), month = month(dates), day = day(dates))
 
 
# would like to be able to get the following result:
 
 test_df
%>% group_by_("year", "month") %>% summarise(sum = sum(ints))
 
 
# but would like to be able do so programmatically, as in the two failing code examples below:
 
 
## this fails
 test_df
%>% group_by_( my_groups[my_groups >= "month"]) %>% summarize(sum = sum(ints))

 
## i think it's a quoting issue, but something like this also fails
 
 test_df %>% group_by_( paste(my_groups[my_groups >= "month"], collapse = ", ")) %>% summarize(sum = sum(ints))



Any help is appreciated

ArjunaCap

unread,
Nov 17, 2016, 5:33:38 PM11/17/16
to manipulatr
So, here was the fix- explicitly passing the vector to the .dots argument, after having coerced it to a vector:

test_df %>% group_by_(.dots = as.character(my_groups[my_groups >= "month"])) %>% summarize(sum = sum(ints))

I have to re-read the NSE/ lazyeval docs every two months
Reply all
Reply to author
Forward
0 new messages