[英]How to simultaneously use sapply and apply to shorten a multiplicative function in R
I was wondering how I could use sapply
and lapply
simultaneously so that I could avoid writing my function called GG
as it appears below? 我想知道如何同时使用
sapply
和lapply
以便我可以避免编写我的函数GG
因为它出现在下面?
GG = function(x, y) dnorm(250, mean = x, sd = y)*dnorm(265, mean = x, sd = y) *
dnorm(259, mean = x, sd = y)
PS I know if only x
in my function above was varying, the following could work: PS我知道如果我上面的函数中只有
x
变化,以下可能有效:
function(x) sapply(lapply(x, dnorm, x = c(250, 265, 259), 10), prod)
But in my case x
and y
both vary. 但就我而言,
x
和y
都有所不同。
We can use Map
with Reduce
from base R
. 我们可以使用
base R
Map
with Reduce
。 The reason for using Map
is that functions can be applied on corresponding elements of the objects passed into it. 使用
Map
的原因是函数可以应用于传递给它的对象的相应元素。 Here, dnorm
is the function which takes each corresponding element of 'x' and 'y' as the mean
and sd
arguments while it has a constant vector of "x" ( c(250, 265, 259)
). 这里,
dnorm
是将'x'和'y'的每个对应元素作为mean
和sd
参数的函数,而它具有常数向量“x”( c(250, 265, 259)
)。 The output of Map
is a list
and we Reduce
the corresponding elements of list
to a single one by multiplying ( *
) Map
的输出是一个list
,我们通过乘以( *
)将list
的相应元素Reduce
为单个元素
GG1 <- function(x, y) Reduce(`*`, Map(dnorm, x = c(250, 265, 259),
mean = list(x), sd = list(y)))
identical(GG(24, 12), GG1(24, 12))
#[1] TRUE
identical(GG(32, 15), GG1(32, 15))
#[1] TRUE
Based on the OP's comments, 根据OP的评论,
x <- seq(10, 40, length= 30)
y <- x
z <- outer(x, y, GG1)
persp(x, y, z , theta = 0, phi = 20, expand = 0.5, col = 'pink')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.