Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn all data.table rows into a list R

Tags:

list

r

data.table

Start with the following data.table:

set.seed(1234)
dt <- data.table(x = runif(3), y = runif(3), z = runif(3))

print(dt)
#         x         y           z
#1: 0.1137034 0.6233794 0.009495756
#2: 0.6222994 0.8609154 0.232550506
#3: 0.6092747 0.6403106 0.666083758

And turn it into a list in the following structure:

print(dt2)
#[[1]]
#[1] 0.1137034 0.6233794 0.009495756
#
#[[2]]
#[1] 0.6222994 0.8609154 0.2325505
#
#[[3]]
#[1] 0.6092747 0.6403106 0.6660838

I've been studying the answers to this question, but have not been able to figure out how to do it for all rows of a data.table at once without applying a looping function. I'm trying to avoid a looping function because of the number of rows in the actual data.table.

like image 832
bshelt141 Avatar asked Mar 11 '23 11:03

bshelt141


1 Answers

You can use the data.table::transpose() function:

transpose(as.list(dt))

#[[1]]
#[1] 0.113703411 0.623379442 0.009495756

#[[2]]
#[1] 0.6222994 0.8609154 0.2325505

#[[3]]
#[1] 0.6092747 0.6403106 0.6660838
like image 58
Psidom Avatar answered Mar 13 '23 12:03

Psidom