geotheory
geotheory

Reputation: 23650

Appending list index number to matrix items as a new column

Simple question no doubt. Taking this starting point:

l = matrix(1:6, ncol=2)
lst = list(l, l)

How can I add the list index as a fresh column to each matrix? e.g.

[[1]]
     [,1] [,2] [,3]
[1,]    1    4    1
[2,]    2    5    1
[3,]    3    6    1

[[2]]
     [,1] [,2] [,3]
[1,]    1    4    2
[2,]    2    5    2
[3,]    3    6    2

... assuming the matrices have varying numbers of rows. I've attempted various permutations of lapply with no luck. Thanks in advance.

Upvotes: 3

Views: 157

Answers (2)

thelatemail
thelatemail

Reputation: 93813

Slightly simpler. Practically any problem involving applying a function to each element of two (or 3, or n) objects in order can be given an mapply or Map solution (thanks, @mnel):

mapply(cbind, lst, seq_along(lst), SIMPLIFY=FALSE)
# ...and with Map being a wrapper for mapply with no simplification
Map(cbind, lst, seq_along(lst))

[[1]]
     [,1] [,2] [,3]
[1,]    1    4    1
[2,]    2    5    1
[3,]    3    6    1

[[2]]
     [,1] [,2] [,3]
[1,]    1    4    2
[2,]    2    5    2
[3,]    3    6    2

Upvotes: 3

Arun
Arun

Reputation: 118799

lapply(seq_along(lst), function(idx) {
    unname(cbind(lst[[idx]], idx))
})

Upvotes: 2

Related Questions