3

I need to create a list from rows of a dataframe in the following format:

df <- data.frame(y1 = c("a", "d"), y2 = c("b", "e"), y3 = c("c", "f"))
df$y1 <- as.character(df$y1)
df$y2 <- as.character(df$y2)
df$y3 <- as.character(df$y3)
x <- list(
  list(y1 = df$y1[1],
       y2 = df$y2[1],
       y3 = df$y3[1]),
  list(y1 = df$y1[2],
       y2 = df$y2[2],
       y3 = df$y3[2])
)

> x
[[1]]
[[1]]$`y1`
[1] "a"

[[1]]$y2
[1] "b"

[[1]]$y3
[1] "c"


[[2]]
[[2]]$`y1`
[1] "d"

[[2]]$y2
[1] "e"

[[2]]$y3
[1] "f"

This is an example when there are two rows in the dataframe. How can I achieve this when the number of rows in the dataframe is variable? So for every row in the dataframe, there should be a list.

Stan
  • 480
  • 1
  • 5
  • 18

3 Answers3

3

We may also use apply by going over the rows and applying as.list to each:

apply(df, 1, as.list)
[[1]]
[[1]]$y1
[1] "a"

[[1]]$y2
[1] "b"

[[1]]$y3
[1] "c"


[[2]]
[[2]]$y1
[1] "d"

[[2]]$y2
[1] "e"

[[2]]$y3
[1] "f"
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
1

We first split every row of the dataframe and then for every row we convert each element into separate list element using as.list

lapply(split(df, 1:nrow(df)), as.list)


#$`1`
#$`1`$y1
#[1] "a"

#$`1`$y2
#[1] "b"

#$`1`$y3
#[1] "c"


#$`2`
#$`2`$y1
#[1] "d"

#$`2`$y2
#[1] "e"

#$`2`$y3
#[1] "f"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

We can use transpose from purrr

library(purrr)
transpose(df)
#[1]]
#[[1]]$y1
#[1] "a"

#[[1]]$y2
#[1] "b"

#[[1]]$y3
#[1] "c"


#[[2]]
#[[2]]$y1
#[1] "d"

#[[2]]$y2
#[1] "e"

#[[2]]$y3
#[1] "f"
akrun
  • 874,273
  • 37
  • 540
  • 662