2015-03-08 103 views
0

我有下一個問題試圖將列表轉換爲數據框,列表的唯一元素是它自己的列。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

+2

請提供'dput'列表中。 – 2015-03-08 20:44:40

回答

1

我建議使用「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

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 
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安裝它。