Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data.table to list of rows; better ways?

Tags:

list

r

data.table

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

like image 673
Herman Avatar asked Sep 11 '25 02:09

Herman


1 Answers

Use apply by rows:

x.list.3 <- apply(x.dt,1,as.list)
like image 156
Marat Talipov Avatar answered Sep 12 '25 17:09

Marat Talipov