简体   繁体   中英

Sapply on User Defined Function

What follows is a simplified version of my problem which is much easier to explain than my original one. Assume I have a vector of parameters

par<-c(0.2,0.5,0.7,0.3,0.9,1,1.2,1.8,1.5)

and a list called total defined as

total
[[1]]
[1] 0.2 0.6 0.8 0.3 0.9

[[2]]
[1] 0.2 0.6 0.8 0.3 0.9 0.2 0.8 0.3 0.9 0.2 0.6 0.3 0.9

[[3]]
[1] 0.2 0.6 0.8 0.3 0.9 0.2 0.8 0.3 0.9 0.2 0.6 0.3 0.9

Now, lets say that I would like to apply the function mean to each one of the 3 elements of the list and each time multiply the result by a function of two parameters selected from par . However, the parameters to be selected change with each iteration of sapply . For example, when I compute the mean for the 1st element of the list, I want to multiply the result times sqrt(par[2]*par[3]) , while when calculating the mean of the second element in the list I want to multiply the result times sqrt(par[5]*par[6]) , etc...

I know I can use sapply to get the mean of each element in total by doing

sapply(total, mean)

but how do I tell sapply to do the rolling multiplication of the result? Should I use rapply ?

Using recyclying you can filter your par vector, to skip one element and then pick the next two.

par <- c(0.2,0.5,0.7,0.3,0.9,1,1.2,1.8,1.5)
xx <- par[c(FALSE,TRUE,TRUE)]

Then tapply to split vector xx by each pair and compute the sqrt:

 sqrt_xx <-  
 tapply(xx,rep(1:(length(xx)/2),each=2),function(x)sqrt(prod(x))))

Then using mapply :

mapply(function(x,y)mean(x)*y, ,total,sqrt_xx)
0.3313005 0.5108295 0.8847826

Where total is :

dput(total)
list(c(0.2, 0.6, 0.8, 0.3, 0.9), c(0.2, 0.6, 0.8, 0.3, 0.9, 0.2, 
0.8, 0.3, 0.9, 0.2, 0.6, 0.3, 0.9), c(0.2, 0.6, 0.8, 0.3, 0.9, 
0.2, 0.8, 0.3, 0.9, 0.2, 0.6, 0.3, 0.9))

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