library(tidyverse)
library(ggplot2) for diamonds dataset
I'm having trouble getting my function to work. What I'm trying to do, using the diamonds dataset form ggplot2 for this example, is to dplyr::group_by "cut" and "color", then dplyr::summarise to get counts. I used rlang and purrr to output both summaries of counts into list, then rename one of the columns, and bind them with dplyr::map_df. Finally, I want to reorder the "Cut" column based on another vector called "Order". The function works until I try to incorporate the row reordering...
This might not make sense for this data, but this is just for an example and it makes sense for my real data.
Anyways, the code below works...
Groups<-list("cut","color")
Groups<-Groups%>%
map_df(function(group){
syms<-syms(group)
diamonds%>%
group_by(!!!syms)%>%
summarise(Count=n())%>%
set_names(c("Cut","Count"))
})
And next, I want to reorder the rows based on the "Order" vector, which also works.
Order<-c("Good","Very Good","Premium","Ideal","Fair","E","F","G","D","H","J","I")
Groups%>%slice(match(Order, Cut))
However, this is where I'm stuck. I'm trying to do all this in one function, but it doesn't seem to work. I feel like I'm missing something small...
Fun<-function(df){
Order<-c("Good","Very Good","Premium","Ideal","Fair","E","F","G","D","H","J","I")
Groups<-list("cut","color")
Groups<-Groups%>%
map_df(function(group){
syms<-syms(group)
df%>%
group_by(!!!syms)%>%
summarise(Count=n())%>%
set_names(c("Cut","Count"))%>%
slice(match(Order,Cut))
return(df)
})
}
Here is another attempt...
Fun<-function(df){
Order<-c("Good","Very Good","Premium","Ideal","Fair","E","F","G","D","H","J","I")
Groups<-list("cut","color")
Groups<-Groups%>%
map_df(function(group){
syms<-syms(group)
df%>%
group_by(!!!syms)%>%
summarise(Count=n())%>%
set_names(c("Cut","Count"))
df<-df%>%slice(match(Order,Cut))
return(df)
})
}
What am I missing here?