我真的不习惯使用功能,我不能让ggplot与它们一起工作。
出于某种原因,这有效:
function_factory <- function(x){
times <- function(y) x * y
}
simple_application <- function(z1, z2){
times_z1 <- function_factory(z1)
times_z2 <- function_factory(z2)
times_z1(3) * times_z2(3)
}
simple_application(3, 3)
但这不是:
plot_times <- function(z1, z2){
times_z1 <- function_factory(z1)
times_z2 <- function_factory(z2)
library(ggplot2)
ggplot(data = data.frame(x = 0), mapping = aes(x = x)) +
stat_function(fun = "times_z1", xlim = c(1, 1000)) +
stat_function(fun = "times_z2", xlim = c(1, 1000))
}
plot_times(3, 4)
我刚收到以下错误:
> plot_times(3, 4)
Warning messages:
1: Computation failed in `stat_function()`:
object 'z1' not found
2: Computation failed in `stat_function()`:
object 'z2' not found
我还有一些并发症,但我希望如果我能解决这个问题,我也可以解决自己的问题。 “ 我很确定这与环境有关,但我无法弄清楚如何修复它。
请注意,在功能工厂中,这很有效:
times_three <- function(x) 3 * x
times_four <- function(x) 4 * x
ggplot(data = data.frame(x = 0), mapping = aes(x = x)) +
stat_function(fun = "times_three", xlim = c(1, 1000)) +
stat_function(fun = "times_four", xlim = c(1, 1000))
答案 0 :(得分:2)
要stat_function
发送"function"
,而不是get("function")
的结果。例如,而不是stat_function(fun = "times_z1", xlim = c(1, 1000))
做stat_function(fun = get("times_z1"), xlim = c(1, 1000))
。
plot_times <- function(z1, z2){
library(ggplot2)
times_z1 <- function_factory(z1)
times_z2 <- function_factory(z2)
ggplot(data = data.frame(x = 0), mapping = aes(x = x)) +
stat_function(fun = get("times_z1"), xlim = c(1, 1000)) +
stat_function(fun = get("times_z2"), xlim = c(1, 1000))
}
结果:
plot_times(3, 4)