incorrect number of dimensions and incorrect number of subscripts in array

You need to convert your data frames into matrices before you do the assignment:

l <- list(data.frame(x=1:2, y=3:4), data.frame(x=5:6, y=7:8))
arr <- array(dim=c(2, 2, 2))
arr[,,1] <- as.matrix(l[[1]])
arr[,,2] <- as.matrix(l[[2]])
arr
# , , 1
# 
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    4
# 
# , , 2
# 
#      [,1] [,2]
# [1,]    5    7
# [2,]    6    8

You can actually build the array in one line with the unlist function applied to a list of the matrices you want to combine:

arr2 <- array(unlist(lapply(l, as.matrix)), dim=c(dim(l[[1]]), length(l)))
all.equal(arr, arr2)
# [1] TRUE

Leave a Comment