Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapply and two lists

Tags:

list

r

apply

I'm trying to use mapply to combine two lists (A and B). Each element is a dataframe. I'm trying to rbind the dataframes in A to the corresponding dataframes in B. The following returns what I would like in combo1:

num = 10
A<-list()
B<-list()
for (j in 1:num){
    A[[j]] <- as.data.frame(matrix(seq(1:9),3,3))
    B[[j]] <- as.data.frame(matrix(seq(10:18),3,3))
}

combo1<-list()
for (i in 1:num){
    combo1[[i]] <-rbind(A[[i]], B[[i]])  
}

I'm trying to use mapply to do the same, but I can't get it to work:

combo2<-list()
combo2<-mapply("rbind", A, B)

I was hoping someone could please help me

like image 490
user1375871 Avatar asked Jan 15 '13 00:01

user1375871


1 Answers

You were very close!

## Make this a more _minimal_ reproducible example
A <- A[1:2]
B <- B[1:2]

## Override default attempt to reduce results to a vector, matrix, or other array
mapply("rbind", A, B, SIMPLIFY=FALSE)
# [[1]]
#   V1 V2 V3
# 1  1  4  7
# 2  2  5  8
# 3  3  6  9
# 4  1  4  7
# 5  2  5  8
# 6  3  6  9
# 
# [[2]]
#   V1 V2 V3
# 1  1  4  7
# 2  2  5  8
# 3  3  6  9
# 4  1  4  7
# 5  2  5  8
# 6  3  6  9
like image 93
Josh O'Brien Avatar answered Oct 30 '22 03:10

Josh O'Brien