Maximilian
Maximilian

Reputation: 4229

Subdivide elements of a list into separate columns

I'm trying to subdivide elements of a list into separate columns.

Sample data:

d <- list(c(1,2,3,4,5,6,7,8),c(1,2,3,4,5,6,7,8))

This is a solution for 1 elements of a list:

numrows <- (row(as.matrix(d[[1]])) %% 2)
TabNum <- sapply(1:2, function(x) as.matrix(d[[1]])[numrows==numrows[x,], ,drop=FALSE])

How do I do this efficiently for a whole list?

Here is start, but later I found it troublesome to compbine with sapply, anyway this is real hack, there must be neater solution.

numrows.list <- lapply(1:length(d), function(i) (row(as.matrix(d[[i]])) %% 2))

So for the d list there would be 4 columns. So the desired output is:

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

Upvotes: 2

Views: 74

Answers (1)

David Arenburg
David Arenburg

Reputation: 92292

This seem to work here

do.call(cbind, lapply(d, function(x) matrix(x, ncol = 2, byrow = TRUE)))
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    1    2
# [2,]    3    4    3    4
# [3,]    5    6    5    6
# [4,]    7    8    7    8

Upvotes: 2

Related Questions