简体   繁体   中英

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?

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:

     function(x) sapply(lapply(x, dnorm, x = c(250, 265, 259), 10), prod)

But in my case x and y both vary.

We can use Map with Reduce from base R . The reason for using Map is that functions can be applied on corresponding elements of the objects passed into it. 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) ). The output of Map is a list and we Reduce the corresponding elements of list to a single one by multiplying ( * )

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,

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM