Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computation failed for stat_summary, 'what' must be a character string or a function

Tags:

r

ggplot2

I am trying to following the script/example on ChickWeight plotting raw data in "Independent Group T intervals test", but keeps running into the following error for stat_summary function

Code to reproduce here:

library(datasets) 
data(ChickWeight)

library(ggplot2) 
g <- ggplot(ChickWeight, aes(x = Time, y = weight, 
                         colour = Diet, group = Chick))
g <- g + geom_line()

g <- g + stat_summary(aes(group = 1), geom = "line", fun.y = mean, size = 1, color = "black")

g <- g + facet_grid(. ~ Diet)

Error message:
"Computation failed in stat_summary():
'what' must be a character string or a function"

The error message is not very intuitive, I do not even see "what" as a param in the documentation of stat_summary, I did some research and check for others' answers but so far no concrete answer or solution to this problem.

like image 258
Michael Huang Avatar asked Feb 27 '17 17:02

Michael Huang


2 Answers

The reason is that you have a variable called mean in your workspace. So when you call stat_summary …

stat_summary(aes(group = 1), geom = "line", fun.y = mean, size = 1, color = "black")

… R thinks that you’re referring to that variable, rather than the mean function from the {base} package.

R is usually able to disambiguate between functions and other variables, even if they have the same name. However, in this case the disambiguation isn’t working because you’re not calling mean directly but passing it as an argument. The solution is to manually disambiguate the function from the variable by doing either of these things:

  1. In the call to stat_summary, use the fully qualified name base::mean, rather than bare mean.
  2. In the call to stat_summary, use match.fun(mean) instead of bare mean: this will tell R that you want to use a function.
  3. Remove or rename the variable.
like image 71
Konrad Rudolph Avatar answered Oct 26 '22 23:10

Konrad Rudolph


Similar problem for geom_smooth(method=lm, se=FALSE, fullrange=TRUE), I got exactly the same error message. Because I have lm in my global environment.
Just fixed the problem by changing lm to "lm":
geom_smooth(method="lm", se=FALSE, fullrange=TRUE)

like image 26
Guannan Shen Avatar answered Oct 26 '22 22:10

Guannan Shen