Reputation: 189
Below is the data frame and the code that I would like to execute.
As shown below I would like to group_by x
as well as by color
.
x
is a string and hence I have used the group_by_at
function.
df <- data.frame(
color = c("Yellow", "Blue", "Green", "Red", "Magenta"),
values = c(24, 24, 34, 45, 49),
Quarter = c("Period1","Period2" , "Period3", "Period3", "Period1"),
Market = c("Camden", "StreetA", "DansFireplace", "StreetA", "DansFireplace"))
list = c("Market", "Quarter")
df_all <- do.call(rbind, lapply(list, function(x) {
df_l <- df %>%
group_by_at(x) %>%
group_by(color) %>%
summarise(values = sum(values)) %>%
mutate(cut = x) %>%
data.frame()
colnames(df_l)[colnames(df_l) == x] <- "Grouping"
df_l
}))
The issue is that while this code is running it is not grouping by x
. Only when I remove group_by(color)
does it group by x
.
My objective is to group by both x
and color
.
Upvotes: 0
Views: 122
Reputation: 4233
If I understood your problem correctly, include color
and x
in the same group_by
statement:
df_all <- do.call(rbind, lapply(list, function(x){
df_l= df %>% group_by_at(c(x, "color")) %>%
summarise(values = sum(values)) %>%
mutate(cut= x) %>%
data.frame()
colnames(df_l)[colnames(df_l)==x] <- "Grouping"
df_l
}))
This gives:
Grouping color values cut
1 Camden Yellow 24 Market
2 DansFireplace Green 34 Market
3 DansFireplace Magenta 49 Market
4 StreetA Blue 24 Market
5 StreetA Red 45 Market
6 Period1 Magenta 49 Quarter
7 Period1 Yellow 24 Quarter
8 Period2 Blue 24 Quarter
9 Period3 Green 34 Quarter
10 Period3 Red 45 Quarter
Upvotes: 1