r.kaiza
r.kaiza

Reputation: 145

Using objects inside list as function arguments in 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.

Upvotes: 7

Views: 392

Answers (2)

thothal
thothal

Reputation: 20329

Update

As per the commments changed the code to keep only the right solution.


As some of the commentators said, the problem is that B would need to be transposed, to find an elegant solution. You should have a look to library(purrr) because with that the whole problem reduces to:

map2(A, B, ~ rbind(.x, t(.y)))
# $`a`
#      [,1] [,2] [,3]
# [1,]    0    0    0
# [2,]    0    0    0
# [3,]    0    0    0
# [4,]    1    1    1

# $b
#      [,1] [,2] [,3]
# [1,]    0    0    0
# [2,]    0    0    0
# [3,]    0    0    0
# [4,]    1    1    1

What map2 does is that it takes 2 lists and applies the function to each element of these lists. The ~ syntax is a shortcut for function(.)

Upvotes: 1

Aur&#232;le
Aur&#232;le

Reputation: 12819

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

lapply(D, with, rbind(first, as.numeric(second)))

Upvotes: 2

Related Questions