将列表作为数据框架最有效的方法是什么?

编程入门 行业动态 更新时间:2024-10-28 12:25:12
本文介绍了将列表作为数据框架最有效的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

很多时候,我想转换一个列表,其中每个索引具有相同的元素类型到数据帧。例如,我可能有一个列表:

Very often I want to convert a list wherein each index has identical element types to a data frame. For example, I may have a list:

> my.list [[1]] [[1]]$global_stdev_ppb [1] 24267673 [[1]]$range [1] 0.03114799 [[1]]$tok [1] "hello" [[1]]$global_freq_ppb [1] 211592.6 [[2]] [[2]]$global_stdev_ppb [1] 11561448 [[2]]$range [1] 0.08870838 [[2]]$tok [1] "world" [[2]]$global_freq_ppb [1] 1002043

我想将此列表转换为数据帧, index元素是一列。自然(对我)的事情是使用 do.call :

I want to convert this list to a data frame where each index element is a column. The natural (to me) thing to go is to is use do.call:

> my.matrix<-do.call("rbind", my.list) > my.matrix global_stdev_ppb range tok global_freq_ppb [1,] 24267673 0.03114799 "hello" 211592.6 [2,] 11561448 0.08870838 "world" 1002043

直截了当,但是当我尝试将此矩阵转换为数据帧时,列仍然是列表元素,而不是向量:

Straightforward enough, but when I attempt to cast this matrix as a data frame, the columns remain list elements, rather than vectors:

> my.df<-as.data.frame(my.matrix, stringsAsFactors=FALSE) > my.df[,1] [[1]] [1] 24267673 [[2]] [1] 11561448

目前,为了正确地获取数据框架,我使用 unlist 和 as.vector ,然后重新创建数据框:

Currently, to get the data frame cast properly I am iterating over each column using unlist and as.vector, then recasting the data frame as such:

new.list<-lapply(1:ncol(my.matrix), function(x) as.vector(unlist(my.matrix[,x]))) my.df<-as.data.frame(do.call(cbind, new.list), stringsAsFactors=FALSE)

但是,似乎效率很低。有没有更好的方法呢?

This, however, seem very inefficient. Is there are better way to do this?

推荐答案

我想你想要的:

> do.call(rbind, lapply(my.list, data.frame, stringsAsFactors=FALSE)) global_stdev_ppb range tok global_freq_ppb 1 24267673 0.03114799 hello 211592.6 2 11561448 0.08870838 world 1002043.0 > str(do.call(rbind, lapply(my.list, data.frame, stringsAsFactors=FALSE))) 'data.frame': 2 obs. of 4 variables: $ global_stdev_ppb: num 24267673 11561448 $ range : num 0.0311 0.0887 $ tok : chr "hello" "world" $ global_freq_ppb : num 211593 1002043

更多推荐

将列表作为数据框架最有效的方法是什么?

本文发布于:2023-10-25 00:25:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525414.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最有效   框架   方法   数据   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!