2011-08-10 29 views
2

我有一个键/值对列表,并希望将其转换为2d矩阵,其中单元格表示每个键/值组合的计数。下面是一个示例数据帧daply自定义输出对象值

doc_id,link 
1,http://example.com 
1,http://example.com 
2,http://test1.net 
2,http://test2.net 
2,http://test5.net 
3,http://test1.net 
3,http://example.com 
4,http://test5.net 

此刻,我使用的r plyr封装及其那种变换的以下命令:

link_matrix <- daply(link_list, .(doc_id, link), summarise, nrow(piece)) 

下面是结果矩阵对象:

doc_id http://example.com http://test1.net http://test2.net http://test5.net 
    1 List,1    NULL    NULL    NULL    
    2 NULL    List,1   List,1   List,1   
    3 List,1    List,1   NULL    NULL    
    4 NULL    NULL    NULL    List,1 

生成的数组条目很好 - 它们给我的键/值计数;但我实际需要的是结果矩阵中的数值。它应该是这样的:

doc_id http://example.com http://test1.net http://test2.net http://test5.net 
    1 2     0    0    0    
    2 0     1    1    1   
    3 1     1    0    0    
    4 0     0    0    0 

我可以通过遍历矩阵元素,并进行必要的转换做到这一点,但我敢肯定有一个更好的解决方案,让我直接做在daply功能。我只是没有想出如何和欣赏这方面的帮助。

回答

3

你可以通过你的代码如下简化做到这一点(即删除summarise):

daply(link_data, .(doc_id, link), nrow) 

doc_id http://example.com http://test1.net http://test2.net http://test5.net 
    1     2    NA    NA    NA 
    2     NA    1    1    1 
    3     1    1    NA    NA 
    4     NA    NA    NA    1 

然后,如果去除NA值是很重要的,使用数组子集:

aa <- daply(link_data, .(doc_id, link), nrow) 
aa[is.na(aa)] <- 0 
aa 

     link 
doc_id http://example.com http://test1.net http://test2.net http://test5.net 
    1     2    0    0    0 
    2     0    1    1    1 
    3     1    1    0    0 
    4     0    0    0    1 
+0

cool,thx。有用.. – behas

0

使用cast功能从reshape

library(reshape) 
cast(transform(mydf, value = 1), doc_id ~ link)