Suppose I have a dataframe given by:
df <- tibble(x=c(1,2,3),
y=c(4,5,6),
z=c(7,8,9))
# A tibble: 3 x 3
x y z
<dbl> <dbl> <dbl>
1 1 4 7
2 2 5 8
3 3 6 9
How could I turn the data frame into a list of lists, where each list encodes the information about each row like this:
list(list(x=1, y=4, z=7),
list(x=2, y=5, z=8),
list(x=3, y=6, z=9))
NOTE: I benchmarked all the methods presented so far in my answer below.
We could just use transpose
purrr::transpose(df)
-output
[[1]]
[[1]]$x
[1] 1
[[1]]$y
[1] 4
[[1]]$z
[1] 7
[[2]]
[[2]]$x
[1] 2
[[2]]$y
[1] 5
[[2]]$z
[1] 8
[[3]]
[[3]]$x
[1] 3
[[3]]$y
[1] 6
[[3]]$z
[1] 9
Apply as.list
to every row in df
using apply
-
apply(df, 1, as.list)
#[[1]]
#[[1]]$x
#[1] 1
#[[1]]$y
#[1] 4
#[[1]]$z
#[1] 7
#[[2]]
#[[2]]$x
#[1] 2
#[[2]]$y
#[1] 5
#[[2]]$z
#[1] 8
#[[3]]
#[[3]]$x
#[1] 3
#[[3]]$y
#[1] 6
#[[3]]$z
#[1] 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With