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

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

问题描述

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



到目前为止,我已经以下列方式解决了这个问题:但是我想知道是否有更好的方法来处理这个问题。

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

#预先分配列表并填充一个循环
xy.list < - vector(list,nrow(xy 。$)
for(i in 1:nrow(xy.df)){
xy.list [[i]]< - xy.df [i,]
}


解决方案

像这样:

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

如果您希望将 xy.df 的rownames作为输出列表的名称,您可以do:

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


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

解决方案

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))

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

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