[英]R - Convert list of list into data frame
我遇到下一个问题,试图将该列表列表转换为数据框,其中列表的唯一元素是其自己的列。
这就是我现在所拥有的:
> head(data$egg_groups)
[[1]]
name resource_uri
1 Plant /api/v1/egg/7/
2 Monster /api/v1/egg/1/
[[2]]
name resource_uri
1 Plant /api/v1/egg/7/
2 Monster /api/v1/egg/1/
[[3]]
name resource_uri
1 Plant /api/v1/egg/7/
2 Monster /api/v1/egg/1/
[[4]]
name resource_uri
1 Dragon /api/v1/egg/14/
2 Monster /api/v1/egg/1/
[[5]]
name resource_uri
1 Dragon /api/v1/egg/14/
2 Monster /api/v1/egg/1/
[[6]]
name resource_uri
1 Dragon /api/v1/egg/14/
2 Monster /api/v1/egg/1/
我想拥有一个数据框,其中的一项(只是名称)是其自己的一列。
像这样:
Plant Monster Dragon
1 1 1
2 1 1
3 1 1
4 1 1
5 1 1
6 1 1
我已经尝试了图书馆plyr和使用unlist
,到目前为止没有任何效果。 任何提示将不胜感激。 谢谢
编辑:这是dput
pastebin链接: dput
您可以使用rbindlist()
从data.table v1.9.5
如下:
(使用@lukeA的示例)
require(data.table) # 1.9.5+
dt = rbindlist(l, idcol="id")
# id x y
# 1: 1 a 1
# 2: 1 b 2
# 3: 2 b 2
# 4: 2 c 3
dcast(dt, id ~ x, fun.aggregate = length)
# id a b c
# 1: 1 1 1 0
# 2: 2 0 1 1
您可以按照此处的说明进行安装。
我会建议使用mtabulate
从“qdapTools”包。 首先,只需遍历列表并提取相关列作为向量,然后将结果列表用作mtabulate
的输入,如下所示:
library(qdapTools)
head(mtabulate(lapply(L, `[[`, "name")))
# Bug Ditto Dragon Fairy Flying Ground Human-like Indeterminate Mineral Monster
# 1 0 0 0 0 0 0 0 0 0 1
# 2 0 0 0 0 0 0 0 0 0 1
# 3 0 0 0 0 0 0 0 0 0 1
# 4 0 0 1 0 0 0 0 0 0 1
# 5 0 0 1 0 0 0 0 0 0 1
# 6 0 0 1 0 0 0 0 0 0 1
# Plant Undiscovered Water1 Water2 Water3
# 1 1 0 0 0 0
# 2 1 0 0 0 0
# 3 1 0 0 0 0
# 4 0 0 0 0 0
# 5 0 0 0 0 0
# 6 0 0 0 0 0
这是一种实现方法:
(l <- list(data.frame(x = letters[1:2], y = 1:2), data.frame(x = letters[2:3], y = 2:3)))
# [[1]]
# x y
# 1 a 1
# 2 b 2
#
# [[2]]
# x y
# 1 b 2
# 2 c 3
df <- do.call(rbind, lapply(1:length(l), function(x) cbind(l[[x]], id = x) ))
# x y id
# 1 a 1 1
# 2 b 2 1
# 3 b 2 2
# 4 c 3 2
library(reshape2)
dcast(df, id~x, fun.aggregate = function(x) if (length(x)) "1" else "" )[-1]
# a b c
# 1 1 1
# 2 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.