简体   繁体   中英

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

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

使用按行应用:

x.list.3 <- apply(x.dt,1,as.list)

I don't know that this is any less clunky, but this works:

as.list(as.data.table(t(x.dt)))

You transpose the data.table using t() , then declare it to be a data.table again, the make it into a list .

The output:

$V1
[1] " 1" "a" 

$V2
[1] " 2" "b" 

$V3
[1] " 3" "c" 

$V4
[1] " 4" "d" 

$V5
[1] " 5" "e" 

$V6
[1] " 6" "f" 

$V7
[1] " 7" "g" 

$V8
[1] " 8" "h" 

$V9
[1] " 9" "i" 

$V10
[1] "10" "j"

As @akrun noted in the comments, the output here is different from your examples, but it is still each row in a list, so you may find that better or worse.

Edit As @David Arenburg pointed out in the comments,

as.list(unlist(t(x.dt)))

provides the same output as the two examples in the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM