2016-06-21 34 views
2

下面是类似于我的数据集物品的​​一部分:计数标签并创建中的R汇总表

require(dplyr) 
alldata 
site date percent_rank Label 
01A 2013-01-01 0.32   Normal 
01B 2013-01-01 0.12   Low 
01C 2013-01-01 0.76   High 
02A 2013-01-01  0   N/A 
02B 2013-01-01 0.16   Low 
02C 2013-01-01 0.5   Normal 
01A 2013-01-02 0.67   Normal 
01B 2013-01-02 0.01   Low 
01C 2013-01-02 0.92   High 

我分配的每个PERCENT_RANK基于所述值(0至0.25至0.75至1的标签三类)。我现在想生产这种格式的汇总表:

site Low Normal High Missing 
01A 32 47  92 194 
01B 232 23  17 93 
01C 82 265  12 6 

,其中每个站点将有低,中,高值的出现与该网站的标签的所有日期的计数(有一个每年的每一天),并且N/A值将被计算为“缺失”列。

我曾尝试以下:

alldata <- %>% group_by(site) %>% mutate(length(Label == "Low")) 

返回的所有记录的总价值,而不是每个网站“低”的计数,并

alldata <- %>% group_by(site) %>% mutate(length(which(Label == "Low"))) 

返回几个值比记录总数高出一千个。我的想法是,我会重复这个功能,创建四个新的列和四个单独的mutate行(每个类别一个),这将产生我的汇总表。我也尝试过一些aggregate()的变体,尽管函数组件对我的目标不太清楚。这看起来应该是一个非常简单的事情(并且group_by很好地为我计算了百分比排名和相关标签),但我还没有找到解决方案。任何提示都非常感谢!

+0

'dplyr'包中有'count'函数。也许这是有帮助的。 – user2100721

+0

如果你使用'which'长度就足够了,但是使用逻辑向量,'sum'会给出计数。 – akrun

回答

0

我们可以使用dcastdata.table,它也有fun.aggregate,速度非常快。

library(data.table) 
dcast(setDT(alldata), site~Label, length) 

或者用dplyr/tidyr

library(dplyr) 
library(tidyr) 
alldata %>% 
    group_by(site, Label) %>% 
    tally() %>% 
    spread(Label, n) 

一个base R选择是

reshape(aggregate(date~site + Label, alldata, length), 
      idvar = "site", timevar="Label", direction="wide") 
+1

这是完美的!我熟悉'dplyr'和'tidyr'软件包,所以它与我的其他代码格式很好地保持一致。谢谢@akrun,以及所有的快速回应。 – acersaccharum

1

有三种方式dplyr做到这一点。首先是最详细和其他两个使用的便利功能,缩短了代码:

library(reshape2) 
library(dplyr) 

alldata %>% group_by(site, Label) %>% summarise(n=n()) %>% dcast(site ~ Label) 

alldata %>% group_by(site, Label) %>% tally %>% dcast(site ~ Label) 

alldata %>% count(site, Label) %>% dcast(site ~ Label) 
1

为了刚刚产生的汇总表,你可以使用table

with(df, table(site, Label, useNA="ifany"))[, c(2,4,1,3)] 

    Label 
site Low Normal High N/A 
    01A 0  2 0 0 
    01B 2  0 0 0 
    01C 0  0 2 0 
    02A 0  0 0 1 
    02B 1  0 0 0 
    02C 0  1 0 0 

数据

df <- read.table(header=T, text="site date percent_rank Label 
01A 2013-01-01 0.32   Normal 
01B 2013-01-01 0.12   Low 
01C 2013-01-01 0.76   High 
02A 2013-01-01  0   N/A 
02B 2013-01-01 0.16   Low 
02C 2013-01-01 0.5   Normal 
01A 2013-01-02 0.67   Normal 
01B 2013-01-02 0.01   Low 
01C 2013-01-02 0.92   High")