Reputation: 1509
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
Upvotes: 4
Views: 10347
Reputation: 12694
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.
Upvotes: 3