Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using objects inside list as function arguments in lapply

Tags:

r

lapply

I am trying to learn different ways to use to the objects inside a list as the FUN arguments in lapply. Take this data:

A <- list(a = matrix(0, ncol = 3, nrow = 3), b = matrix(0, ncol = 3, nrow = 3))
B <- list(a = matrix(1, ncol = 1, nrow = 3), b = matrix(1, ncol = 1, nrow = 3))
D <- mapply(FUN="list", A, B, SIMPLIFY=F, USE.NAMES=F)
D <- lapply(D, `names<-`, c("first", "second"))
D
[[1]]
[[1]]$`first`
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0

[[1]]$second
     [,1]
[1,]    1
[2,]    1
[3,]    1


[[2]]
[[2]]$`first`
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0

[[2]]$second
     [,1]
[1,]    1
[2,]    1
[3,]    1

Desired result:

[[1]]
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0
[4,]    1    1    1

[[2]]
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0
[4,]    1    1    1

This is how I would normally do it:

lapply(D, function(x) rbind(x$first, as.numeric(x$second)))

Now I am wondering whether there is a way to avoid using function(x) and repeating all those xs. Something like:

lapply(D, "rbind", <args>)

How can I let rbind (or any other function) know that I am referring to objects within the frame of lapply?

Thank you,

K.

like image 600
r.kaiza Avatar asked Aug 24 '18 09:08

r.kaiza


1 Answers

To "avoid using function(x) and repeating all those xs", we could use with():

lapply(D, with, rbind(first, as.numeric(second)))
like image 53
Aurèle Avatar answered Oct 31 '22 05:10

Aurèle