Polar Bear Polar Bear - 3 months ago 8
R Question

How to make a matrix without dimension names from a list

I have a list:

direc <- structure(list(no_trades = 3L, sell_trades = 19L, buy_trades = 18L), .Names = c("no_trades", "sell_trades", "buy_trades"))
# $no_trades
# [1] 3
#
# $sell_trades
# [1] 19
#
# $buy_trades
# [1] 18


I want to make a matrix without dimension names from this list. That would be similar to this matrix structure:

classified <- structure(c(9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13, 9, 6, 13), .Dim = c(3L, 15L))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
# [1,] 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
# [2,] 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
# [3,] 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13


I have tried the following code from another SO question meant for dataframe to matrix conversion:

m2 <- `dimnames<-`(as.matrix(direc), NULL)


But it again gives me a list:


structure(list(3L, 19L, 18L), .Dim = c(3L, 1L))


Thanks in advance for the answer.

Answer

Here the 'direc' is a list and conversion to matrix with as.matrix won't happen directly, but we can change it to matrix with rbind/cbind. The initial direc elements are all integer class. If we need to have numeric class, it needs to be converted

m1 <- `dimnames<-`(do.call(cbind, lapply(direc, as.numeric)), NULL)
dput(m1)
#structure(c(3, 19, 18), .Dim = c(1L, 3L))

If the list elements have unequal lengths, it may be better to pad with NA before doing the cbind

`dimnames<-`(do.call(cbind, lapply(direc, `length<-`, max(lengths(direc)))), NULL)

To understand why as.matrix did not work here, we can check the methods of list

methods(class = "list")
#[1] all.equal     as.data.frame as.data.table as_data_frame
#[5] coerce        escape        melt          Ops           relist       
#[10] sotrunc       within       

It did not have the as.matrix option.

Comments