Hi experienced R users,
It's kind of a simple thing.
I want to sum x
by Group.1
depending on one controllable variable.
I'd like to sum x
by grouping the first two rows when I say something like: number <- 2
If I say 3
, it should sum x
of the first three rows by Group.1
Any idea how I might tackle this problem? Should I write a function? Thank y'all in advance.
Group.1 Group.2 x
1 1 Eggs 230299
2 2 Eggs 263066
3 3 Eggs 266504
4 4 Eggs 177196
The rowSums() function in R can be used to calculate the sum of the values in each row of a matrix or data frame in R.
By using bracket notation on R DataFrame (data.name) we can select rows by column value, by index, by name, by condition e.t.c. You can also use the R base function subset() to get the same results. Besides these, R also provides another function dplyr::filter() to get the rows from the DataFrame.
Often you may want to find the sum of a specific set of columns in a data frame in R. Fortunately this is easy to do using the rowSums() function.
If the sums you want are always cumulative, there's a function for that, cumsum
. It works like this.
> cumsum(c(1,2,3))
[1] 1 3 6
In this case you might want something like
> mysum <- cumsum(yourdata$x)
> mysum[2] # the sum of the first two rows
> mysum[3] # the sum of the first three rows
> mysum[number] # the sum of the first "number" rows
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With