简体   繁体   中英

Turn all data.table rows into a 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'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.

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

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