Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

I have a data.frame which I would like to convert to a list by rows, meaning each row would correspond to its own list elements. In other words, I would like a list that is as long as the data.frame has rows.

So far, I've tackled this problem in the following manner, but I was wondering if there's a better way to approach this.

xy.df <- data.frame(x = runif(10),  y = runif(10))

# pre-allocate a list and fill it with a loop

xy.list <- vector("list", nrow(xy.df))

for (i in 1:nrow(xy.df)) {

    xy.list[[i]] <- xy.df[i,]

}

1 Answer

0 votes
by

To convert data frame rows to a list, you can use the split function as follows:

xy.df <- data.frame(x = runif(10),  y = runif(10))

xy.list <- split(xy.df, seq(nrow(xy.df)))

 xy.list

$`1`

          x         y

1 0.1153423 0.3825046

$`2`

          x          y

2 0.9959655 0.09404589

$`3`

          x          y

3 0.3792767 0.04965358

$`4`

          x         y

4 0.5619881 0.8211623

$`5`

         x         y

5 0.732718 0.8293243

$`6`

          x         y

6 0.8708056 0.6547329

$`7`

          x         y

7 0.5721703 0.1328278

$`8`

           x         y

8 0.01103607 0.3418099

$`9`

          x         y

9 0.9063153 0.7313716

$`10`

           x         y

10 0.7706536 0.9072914

> class(xy.list)

[1] "list"

Related questions

0 votes
1 answer
+1 vote
1 answer
asked May 23, 2019 in R Programming by Nigam (4k points)
0 votes
1 answer

Browse Categories

...