Roman Luštrik - 1 year ago 74

R Question

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,]

}

Answer Source

Like this:

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

And if you want the rownames of `xy.df`

to be the names of the output list, you can do:

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