R - 将列表的列表转换为数据框
问题描述:
我有下一个问题试图将列表转换为数据框,列表的唯一元素是它自己的列。R - 将列表的列表转换为数据框
这就是我现在所拥有的:
> 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
引擎收录链接: dput
答
我建议使用“qdapTools”包中的mtabulate
。首先,刚刚经历列表循环和提取相关的列向量,并使用所产生的列表作为输入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
+0
伟大的解决方案!有效。当然,我需要更多地了解这些软件包。希望我可以让你高兴。 – user3276768 2015-03-09 20:50:41
答
下面是做这件事:
(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
答
您可以使用rbindlist()
从data.table v1.9.5
如下:
(使用@卢克A的例子)
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
您可以按照说明here安装它。
请提供'dput'列表中。 – 2015-03-08 20:44:40