Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help understand the error in a function I defined in R

Tags:

r

I am very new to R and just learnt to write simple functions. Can someone help me understand why the following function does not work.

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 the 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)

That gives the same error. Where am I going wrong?

Thanks for your help.

like image 371
Curious2learn Avatar asked Jun 27 '11 19:06

Curious2learn


People also ask

How do I catch exceptions in R?

tryCatchLog() This function evaluates the expression in expr and passes all condition handlers in ... to tryCatch as-is while error, warning and message conditions are logged together with the function call stack (including file names and line numbers). The expression in finally is always evaluated at the end.

How does tryCatch work in R?

tryCatch returns the value associated to executing expr unless there's an error or a warning. In this case, specific return values (see return(NA) above) can be specified by supplying a respective handler function (see arguments error and warning in ? tryCatch ).


2 Answers

The aes function in ggplot2 uses names like library() does, i.e. it takes the name of the argument as the argument. If this is an object, it does not evaluate it but takes the name instead. Here it takes varx as the argument and not what varx evaluates too.

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")
like image 115
Sacha Epskamp Avatar answered Sep 22 '22 17:09

Sacha Epskamp


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

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") 
like image 21
Aniko Avatar answered Sep 25 '22 17:09

Aniko