Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn dataframe into list of lists rowwise?

Tags:

dataframe

r

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.

like image 659
max Avatar asked Dec 08 '22 09:12

max


2 Answers

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
like image 51
akrun Avatar answered Feb 17 '23 09:02

akrun


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
like image 44
Ronak Shah Avatar answered Feb 17 '23 09:02

Ronak Shah