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.

0

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.