简体   繁体   中英

Create a matrix of list without for loop in R

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?

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
rbind(unlist(x), unlist(y)) %*% rbind(z, 1-z, 1)

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