passing arguments to function with a view to plotting with ggplot stat_function

后端 未结 1 742
余生分开走
余生分开走 2021-01-15 02:24

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 repl

相关标签:
1条回答
  • 2021-01-15 03:11

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

    enter image description here

    0 讨论(0)
提交回复
热议问题