I am working with R Shiny for some exploratory data analysis. I have two checkbox inputs that contain only the user-selected options. The first checkbox input contains only the categorical variables; the second checkbox contains only numeric variables. Next, I apply a groupby
on these two selections:
var1 <- input$variable1 # Checkbox with categorical variables var2 <- input$variable2 # Checkbox with numerical variables v$data <- dataset %>% group_by_(var1) %>% summarize_(Sum = interp(~sum(x), x = as.name(var2))) %>% arrange(desc(Sum))
When only one categorical variable is selected, this groupby
works perfectly. When multiple categorical variables are chosen, this groupby
returns an array with column names. How do I pass this array of column names to dplyr
's groupby
?
The group_by() method is used to group the data contained in the data frame based on the columns specified as arguments to the function call.
%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. It is defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).
When working with categorical variables, you may use the group_by() method to divide the data into subgroups based on the variable's distinct categories. You can group by a single variable or by giving in multiple variable names to group by several variables.
With more recent versions of dplyr
, you should use across
along with a tidyselect helper function. See help("language", "tidyselect")
for a list of all the helper functions. In this case if you want all columns in a character vector, use all_of()
cols <- c("mpg","hp","wt") mtcars %>% group_by(across(all_of(cols))) %>% summarize(x=mean(gear))
If you have a vector of variable names, you should pass them to the .dots=
parameter of group_by_
. For example:
mtcars %>% group_by_(.dots=c("mpg","hp","wt")) %>% summarize(x=mean(gear))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With