tidyeval
Creating multiple graphs based upon the column names
A solution using tidyeval approach. We will need ggplot2 v3.0.0 (remember to restart your R session) install.packages(“ggplot2”, dependencies = TRUE) First we build a function that takes column and group names as inputs. Note the use of rlang::sym, rlang::quo_name & !!. Then create 2 name vectors for x- & y- values so that we can … Read more
dplyr: How to use group_by inside a function?
For programming, group_by_ is the counterpart to group_by: library(dplyr) mytable <- function(x, …) x %>% group_by_(…) %>% summarise(n = n()) mytable(iris, “Species”) # or iris %>% mytable(“Species”) which gives: Species n 1 setosa 50 2 versicolor 50 3 virginica 50 Update At the time this was written dplyr used %.% which is what was originally … Read more
Multiple plots in for loop ignoring par
Here is one way to do it with cowplot::plot_grid. The plot_duo function uses tidyeval approach in ggplot2 v3.0.0 # install.packages(“ggplot2”, dependencies = TRUE) library(rlang) library(dplyr) library(ggplot2) library(cowplot) plot_duo <- function(df, plot_var_x, plot_var_y) { if (is.character(plot_var_x)) { print(‘character column names supplied, use ensym()’) plot_var_x <- ensym(plot_var_x) } else { print(‘bare column names supplied, use enquo()’) plot_var_x … Read more
Looping over variables in ggplot
You just need to use aes_string instead of aes, like this: ggplot(data=t, aes_string(x = “w”, y = i)) + geom_line() Note that w then needs to be specified as a string, too.
How to use a variable to specify column name in ggplot
You can use aes_string: f <- function( column ) { … ggplot( rates.by.groups, aes_string(x=”name”, y=”rate”, colour= column, group=column ) ) } as long as you pass the column to the function as a string (f(“majr”) rather than f(majr)). Also note that we changed the other columns, “name” and “rate”, to be strings. If for whatever … Read more