问题
I have a function and a list of arguments.
F <- function(a,b,...) {a^b+b/a}
L <- list("a" = 5, "b" = 2, "c" = 0)
I want to replace one of the arguments ("a", "b" or "c") with an unknown x (or "x") and plot with ggplot's stat_function.
These computations are part of a shiny app, where the user will 1) select a parameter from a drop-down list, say "a", to be the unknown, and 2) use sliders to select values of the other parameters. The numbers 5, 2, 0 in L are the default parameter values, to be used before user interaction. There are several such functions. Here the list of parameters L has an element not used in F.
I've been stuck on this for so long that I can't think straight anymore. Of the many things I've tried, here's one:
# select a parameter to vary:
Y <- "a"
f1 <- function(f = F, l = L, y = Y, x, ...){
l[y] <- x # replace "a" with x
do.call(f, l, ...)
}
# make a stat_function ggplot:
library("ggplot2")
df <- data.frame(x = c(0,10))
p <- ggplot(df, aes(x))
p <- p + stat_function(fun = f1)
print(p)
This returns the following error:
Error in (function (f = F, l = L, y = Y, x, ...) :
argument "x" is missing, with no default
Error in as.environment(where) : 'where' is missing
I have tried several variants, including: setting l[y] <- "x" and using aes_string instead of aes. I have also tried backquotes around x. I have read through the documentation about environments, so I've tried defining an environment, wrapping x and just about everything around eval or quote. I've even tried voodoo. I've lost count of how many hours I've spent on this. A suggestion to read the manual or a hint without an explanation will kill me. 8-) If my question is unclear, please let me know and I will clarify. Thanks!
回答1:
If I understand, Having a multi parameters functions , you want to induce a partial function where you vary one parameter and fix others. Try this for example:
F <- function(a,b,...) {a^b+b/a}
L <- list("a" = 5, "b" = 2, "c" = 0)
f.partial <- function( var = "a",params=L){
params[[var]]=as.name("x")
function(x)do.call(F,params)
}
We can test this for example:
## vary a
f.partial("a")(1)
[1] 3
> F(1,b=L$b)
[1] 3
## vary b
> f.partial("b")(1)
[1] 5.2
> F(1,a=L$a)
[1] 5.2
Testing with ggplot2
:
library("ggplot2")
df <- data.frame(x = seq(0,1,0.1))
ggplot(df, aes(x)) +
stat_function(fun = f.partial("a"),col='blue') +
stat_function(fun = f.partial("b"),col='red')
来源:https://stackoverflow.com/questions/21030596/passing-arguments-to-function-with-a-view-to-plotting-with-ggplot-stat-function