rlistmatrix

Make simplify2array to produce a numeric matrix


I want to bring elements from a list in a matrix using simplify2array and calculate the rowMeans. The problem is that simplify2array produces a matrix, with elements beeing of class list and not numeric:

bar <- list(list(11, 21, 31), list(12, 22, 32))

bar_new <- simplify2array(bar)
#gives[,1] [,2]
#[1,] 11   12  
#[2,] 21   22  
#[3,] 31   32 
rowMeans(bar_new) 
#gives Error: 'x' must be numeric
# does not work as all elements in foo are lists - see class(bar_new[1, 1])

Of course a workaround would be rowMeans(matrix(as.numeric(bar_new), ncol = ncol(bar_new))). But I want to keep it short and simple. So the question is: how can I make simplify2array to produce a "numeric"-matrix?


For completeness, the expected output would be:

foo <- matrix(c(11, 12, 21, 22, 31, 32), byrow = TRUE, nrow = 3)

#gives [,1] [,2]
#[1,]    11   12
#[2,]    21   22
#[3,]    31   32

rowMeans(foo) 
#gives 11.5 21.5 31.5
# works as all elements in foo are numeric - see class(foo[1, 1])

Solution

  • Another way:

    mode(bar_new) <- "numeric"
    rowMeans(bar_new)
    # [1] 11.5 21.5 31.5