Adding a vector to each sublist in list R

I have two lists with the same structure. I would like to combine them to get the next desired result.

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
+3
source share
2 answers

Since the length of the corresponding elements in listboth “A” and “B” is not the same, we could save this in list. One convenient function Mapdoes this on the corresponding elements list"A" and "B".

lst <- Map(list, A, B)

If we want to keep this as matrixwith NAto fill in unequal lengths, one option is stri_list2matrixfrom library(stringi). The output will be matrix, but we need to convert the output characterback tonumeric

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
+4
source

" " . ? ?

mapply FUN, :

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

.

+1

Source: https://habr.com/ru/post/1677110/


All Articles