在一个变量上折叠数据框 [英] Collapsing a data frame over one variable

查看:155
本文介绍了在一个变量上折叠数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下格式的数据框:

I have a data frame in the following format:

Site    Year    Month   Count1  Count2  Count3  Patch
1        1        May     15      12      10      1
1        1        May     8        0      5       2
1        1        May     3         1      2      3
1        1        May     4        4      1       4
1        1        June    6       5       1       1
1        1        June    9        1      3       2
1        1        June    3       0       0       3
1        1        June    5       5       2       4
1        1        July    4       0       3       1
..........

我希望将数据框架在整个补丁级别将三个计数变量相加。即

And I wish to collapse the data frame across the levels of patch such that the three count variables are summed. i.e.

Site    Year    Month   Count1  Count2  Count3  
1        1        May     30      17      18     
1        1        June    23      11       6       
1        1        July     4       0       3      
.........

我已经查看了汇总和自定义命令,但是它们似乎并没有按照需要在修补程序中相加。

I've looked at the aggregate and tapply commands, but they do not seem to sum across patch as required.

有人可以告诉我们一个命令,

Can somebody please advise on a command that will convert the data accordingly.

谢谢。

推荐答案

> ( a <- aggregate(.~Site+Year+Month, dat[-length(dat)], sum) )
#   Site Year Month Count1 Count2 Count3
# 1    1    1  July      4      0      3
# 2    1    1  June     23     11      6
# 3    1    1   May     30     17     18

其中 dat 是您的数据。

请注意,您的七月份的发布结果似乎不正确。

Note that your July results in the post are seem to be incorrect.

对于订单中的结果的原始数据,您可以使用

For the result in the order of the original data, you can use

> a[order(as.character(unique(dat$Month))), ]
#   Site Year Month Count1 Count2 Count3
# 3    1    1   May     30     17     18
# 2    1    1  June     23     11      6
# 1    1    1  July      4      0      3

这篇关于在一个变量上折叠数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆