I want to convert an R data.table into a list of rows (each row being represented by a list). So far I have found two ways of doing this:
library(data.table)
x.dt = data.table(x = seq(1, 10), y = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"), key="x")
# Using lapply & split
x.list.1 = lapply(split(x.dt, rownames(x.dt)), as.list)
# Using Lapply
x.list.2 = lapply(as.list(1:nrow(x.dt)), function(row) as.list(x.dt[row[1],]))
They both seem a bit clunky to me. Is there a better (more concise) way of doing this?
Kind regards, Herman
Use apply by rows:
x.list.3 <- apply(x.dt,1,as.list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With