Barnaby
Barnaby

Reputation: 1480

Adding a vector to each sublist within a list R

I have two lists with the same structure. I would like to combine them as to produce the following desired output.

A <- list(c(1,2,3,2,1,4),c(7,3,1,2,2,1),c(2,3,7,2,2,8))
B <- list(c(2,1,3,2),c(3,1,5,2),c(2,4,5,1))

# Desired Output

[[1]]
    [1] 1 2 3 2 1 4
    [1] 2 1 3 2
[[2]]
    [1] 7 3 1 2 2 1
    [1] 3 1 5 2
[[3]]
    [1] 2 3 7 2 2 8
    [1] 2 4 5 1

# I have tried with the items beloww and nothing works as to produce the shown desired output. Would you happen to know on how to combine the two vectors as to produce the outcome below. 

c
cbind(A,B)
     A         B        
[1,] Numeric,6 Numeric,4
[2,] Numeric,6 Numeric,4
[3,] Numeric,6 Numeric,4

merge
append

Upvotes: 4

Views: 1576

Answers (2)

akrun
akrun

Reputation: 887118

As the length of the corresponding list elements in both 'A' and 'B' are not the same, we could keep this in a list. One convenient function is Map to do this on corresponding list elements of 'A' and 'B'.

lst <- Map(list, A, B)

If we want to keep this as a matrix with NA to pad the unequal length, one option is stri_list2matrix from library(stringi). The output will be a matrix, but we need to convert the character output back to numeric

library(stringi)
lst1 <- lapply(lst, stri_list2matrix, byrow=TRUE)
lapply(lst1, function(x) matrix(as.numeric(x),nrow=2))
#[[1]]
#      [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    1    2    3    2    1    4
#[2,]    2    1    3    2   NA   NA

#[[2]]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    7    3    1    2    2    1
#[2,]    3    1    5    2   NA   NA

#[[3]]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    2    3    7    2    2    8
#[2,]    2    4    5    1   NA   NA

Upvotes: 5

RockScience
RockScience

Reputation: 18580

Your 'desired output' is not very clear. What is inside the first element of the list? Is it another list?

You can try to use mapply, and change the FUN to get different output format:

mapply(FUN = list, A, B, SIMPLIFY = FALSE)

Which gives you a list inside a list.

Upvotes: 1

Related Questions