[R] rowsum
jim holtman
jholtman at gmail.com
Wed Oct 20 14:00:12 CEST 2010
Another option to consider:
> x
A B C
1 89 1 140
2 89 6 20
3 89 29 137
4 89 52 13
5 89 57 10
6 89 97 23
7 89 1 37
8 89 1 12
9 89 1 3
10 52 1 11
11 52 1 31
12 52 1 16
13 52 1 6
14 52 1 10
15 52 1 13
16 52 1 10
17 52 1 25
18 52 1 2
19 52 59 38
20 52 97 75
21 57 1 14
22 57 1 13
23 57 1 14
24 57 114 12
25 57 1 23
26 57 6 26
> require(sqldf)
> sqldf("select A, B, sum(C) from x group by A, B")
A B sum(C)
1 52 1 124
2 52 59 38
3 52 97 75
4 57 1 64
5 57 6 26
6 57 114 12
7 89 1 192
8 89 6 20
9 89 29 137
10 89 52 13
11 89 57 10
12 89 97 23
>
On Wed, Oct 20, 2010 at 5:42 AM, xtracto <b2017700 at lhsdv.com> wrote:
>
> Hello,
>
> I am trying to achieve something which I *think* is possible using rowsum,
> but a little help should be useful:
>
> Consider the following dataframe DF0:
> A B C
> 89 1 140
> 89 06 20
> 89 29 137
> 89 52 13
> 89 57 10
> 89 97 23
> 89 1 37
> 89 1 12
> 89 1 3
> 52 1 11
> 52 1 31
> 52 1 16
> 52 1 6
> 52 1 10
> 52 1 13
> 52 1 10
> 52 1 25
> 52 1 2
> 52 59 38
> 52 97 75
> 57 1 14
> 57 1 13
> 57 1 14
> 57 114 12
> 57 1 23
> 57 06 26
>
>
> I need create a new dataframe containing the sums of all the rows where B =
> 1 for the different values of A, keeping the rows with other B values the
> same. That is, for this data sample, the result I expect is something like
> this (the order of the rows does not matter):
>
> A B C
> 89 1 192 #From adding up: [140 + 37 + 12 + 3]
> 89 06 20
> 89 29 137
> 89 52 13
> 89 57 10
> 89 97 23
> 52 1 124 # From adding up: [11 + 31 + 16 + 6 + 10 + 13 + 10 + 25 + 2]
> 52 59 38
> 52 97 75
> 57 1 64 #From adding up: [14 +13 +14 +23]
> 57 114 12
> 57 06 26
>
>
> Now, I now it should be possible to first separate the data in two sets,
> where
> DF1 <- DF0[DF0$B != 1,]
> DF2 <- DF0[DF0$B == 1,]
>
> Then I should apply sumrow to DF2 with some "group" vector, but I do not
> know where to go from here.
>
> Can anyone help?
> Thanks in advance!
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/rowsum-tp3003551p3003551.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list