data.frame 行到列表 [英] data.frame rows to a list

查看:35
本文介绍了data.frame 行到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.frame,我想按行将其转换为列表,这意味着每一行都对应于它自己的列表元素.换句话说,我想要一个只要 data.frame 有行的列表.

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

推荐答案

像这样:

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

如果你想让 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))

这篇关于data.frame 行到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆