Reputation: 1981
I have two list in R and I want to create the result in a matrix for different z
values. Means that at the end I have matrix with 2 rows and 10 columns.
x = list(a = 1, b = 2, c = 3)
y = list(a = 4, b = 5, c = 3)
z = seq(0, 1, len = 10)
w = list(a1 = z * x$a + (1-z) * x$b + x$c , b1 = z * y$a + (1-z) * y$b + y$c)
How can I do this without for loop in R?
Upvotes: 1
Views: 282
Reputation: 42629
How about something like this (prior to the edit of the question, x
and y
are of length 2):
d <- list(x, y)
t(sapply(d, function(x) z*x$a + (1-z)*x$b))
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 2 1.888889 1.777778 1.666667 1.555556 1.444444 1.333333 1.222222 1.111111 1
## [2,] 5 4.888889 4.777778 4.666667 4.555556 4.444444 4.333333 4.222222 4.111111 4
Upvotes: 1