Question

have a question concerning the use of mapply.

Consider the following 2 cases: Case 1 showing a simplified example of what I wish to do. I use mapply to transform my vector k element-wise with the functions stored in vector trans. This works (related to this question)

In Case 2 I wish to do something similar, however, I want extra function arguments (here, stored in a).But I might want n function arguments. What I get in this example is a 3x3 matrix with the expected results on the diagonal. I only want the computed output of the diagonal. How?

k <- seq(1:3)
# Case 1 -----------------------------------------------------------------------
trans <- c(function(x) x, function(x) 1/x, function(x) x^2)             
# transform vektors elementwise with functions in a "transform" vektor
ktrans   <- mapply(function(f, x) f(x), trans, k)

# 2 -----------------------------------------------------------------------
k <- seq(1:3)
a <- rep(2,3)
transa <- c(function(x,a) x*a, function(x,a) 1/x*a, function(x,a) x^2*a)
ktransa   <- mapply(function(f, x,a) f(x,a), transa, MoreArgs= list(x = k, a= a))

> diag(ktransa)
[1]  2  1 18
Was it helpful?

Solution

Solution:

Instead of using a list to send the arguments to the function, I did it explicitly:

# 3 --- Example with n arguments -----------------------------------
k <- seq(1:3)
a <- rep(2,3)
transa <- c(function(x,a) x*a, function(x,a) 1/x*a, function(x,a) x^2*a)
ktransa   <- mapply(function(f, x, a) f(x,a), transa,x = k , a = a)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top