我正在尝试让 ggplot 绘制函数,例如
library(ggplot2)
dframe <- data.frame(x = c(0:30), y = c(0:30 * 10))
LVB = function(t, Linf, K, t0) {
Linf*(1-exp(-K*(t-t0)))
}
parms = list("Linf" = 209, "K" = 0.47, "t0" = -1.61)
g = ggplot(dframe, aes(x, y))
g = g + stat_function(fun = function(x) LVB(x, 200, 0.6, -1), color = "red")
g
但是我希望能够将“LVB”函数的参数存储在列表中 - 在这里,我已经定义了它们,但通常它们来自模型:
parms = list("Linf" = 209, "K" = 0.47, "t0" = -1.61)
我想将以下行(我的模型参数)添加到图中,使其看起来像这样:
g + stat_function(fun = function(x) LVB(x, 209, 0.47, -1.61), color = "blue")
但是,无论我做什么,stat_function 都不会获取我的列表...我在这里缺少什么?
g + stat_function(fun = function(x) LVB(x, parms), color = "blue")
g
Warning message: Computation failed in
stat_function()
: argument "K" is missing, with no default
------------
编辑: Stibu回答了这个问题并提供了一个很好的解决方案。阅读“FSA”包中的函数,我认为这个也可以解决这个问题 - 它询问参数的长度,如果是三个,它定义每个参数。偷偷摸摸但有效。
LVB = function(t, Linf, K, t0)
{
if (length(Linf) == 3) {
K <- Linf[[2]]
t0 <- Linf[[3]]
Linf <- Linf[[1]]
}
Linf*(1-exp(-K*(t-t0)))
}
最佳答案
这与 stat_function()
无关,而是与 LVB()
本身有关。您已使用语法定义了它
LVB(t, Linf, K, t0)
你必须尊重这一点。如果你运行
LVB(t, parms)
该函数认为应该对 Linf
使用 parms
并认为 K
和 t0
缺失,这这就是你收到错误的原因。
您可以使用do.call()
来解决这个问题。 do.call()
可用于将函数参数作为列表传递。所以下面三行是等价的
LVB(3, 5, 2, 1)
do.call(LVB, list(3, 5, 2, 1))
do.call(LVB, list(t = 3, Linf = 5, K = 2, t0 = 1))
您可以在 stat_function()
中使用它,如下所示:
g + stat_function(fun = function(x) do.call(LVB, c(list(x), parms)), color = "blue")
或者,您也可以更改函数定义:
LVB_list <- function(t, parms) {
parms$Linf*(1-exp(-parms$K*(t-parms$t0)))
}
g + stat_function(fun = function(x) LVB_list(x, parms), color = "blue")
关于r - Stat_function 将不接受参数列表(ggplot),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35924949/