Turn all data.table rows to list R

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 studied the answers to this question , but could not figure out how to do this for all rows of the data table. without applying a cyclic function. I am trying to avoid a loop function due to the number of rows in the actual data table.

+4
source share
1 answer

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

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
+7
source

Source: https://habr.com/ru/post/1663027/


All Articles