I have a single big text file which looks as follows:
tag colony diff
1035 03 498
1035 03 -44365
1035 03 -66652
1035 04 234234
1035 04 -343
1035 04 -23423
1037 10 234234
1037 10 -343
1037 10 -23423
Most 'tags' only have a single colony, such as 1037 in the above example. However, some have 2, such as 1036 having both 03 and 04. What I would like to do is sum the diff column for each tag, but separately for each colony, so the output would be something like this.
tag colony total
1035 03 -110 519
1035 04 210 648
1037 10 210 648
So far (I've been working in R), I have been using aggregate:
x2 = aggregate(x$diff, by=list(tag=x$tag), FUN=sum)
But this would count all tags together, irrespective of colony. Is there a way of 'adding another level', so to speak, into the aggregate function, so that it counts the colonies seperately?
Thanks
We can use dplyr
library(dplyr)
df1 %>%
group_by(tag, colony) %>%
summarise(total = sum(diff))
Or data.table
library(data.table)
setDT(df1)[, .(total = sum(diff)), .(tag, colony)]
x2 <- aggregate(x$diff, by=list(x$tag,x$colony), FUN=sum)
或等效地作为公式x2 <- aggregate(diff~tag+colony,data=x,FUN=sum)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.