Help understand the error in the function defined in R

I am very new to R and just learned how to write simple functions. Can someone help me understand why the following function is not working.

fboxplot <- function(mydataframe, varx, vary) { p <- ggplot(data=mydataframe, aes(x=varx, y=vary)) p + geom_boxplot() } col1 = factor(rep(1:3, 3)) col2 = rnorm(9) col3 = c(rep(10,5), rep(20,4)) df = data.frame(col1 = col1, col2 = col2, col3 = col3) 

Now, if I call fboxplot function

 fboxplot(df, col1, col2) 

I get the error Error in eval(expr, envir, enclos): object varx not found . I also tried

 fboxplot(df, varx = col1, vary = col2) 

This gives the same error. Where am I mistaken?

Thank you for your help.

+5
source share
2 answers

The aes function in ggplot2 uses library() type names, i.e. accepts the argument name as an argument. If it is an object, it does not evaluate it, but instead takes a name. Here it takes varx as an argument, not what varx also evaluates to.

It works if you use aes_string() instead and use characters as arguments in the fboxplot() call:

 fboxplot <- function(mydataframe, varx, vary) { p <- ggplot(data=mydataframe, aes_string(x=varx, y=vary)) p + geom_boxplot() } col1 = factor(rep(1:3, 3)) col2 = rnorm(9) col3 = c(rep(10,5), rep(20,4)) df = data.frame(col1 = col1, col2 = col2, col3 = col3) fboxplot(df, "col1", "col2") 
+7
source

The problem is that you go through the varx and vary , and the aes function expects variable names (but not as strings). One way to fix this is to use the aes_string function, into which you can pass variable names as strings (still not vectors):

The following should work:

 fboxplot2 <- function(mydataframe, varx, vary) { p <- ggplot(data=mydataframe, aes_string(x=varx, y=vary)) p + geom_boxplot() } fboxplot2(df, "col1", "col2") 
+6
source

Source: https://habr.com/ru/post/950807/


All Articles