Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how to sum certain rows of a data frame with certain logic?

Tags:

r

sum

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
like image 612
purpleblau Avatar asked Nov 06 '13 20:11

purpleblau


People also ask

How do I sum specific rows in R?

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.

How do I select certain rows of data 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.

How do I sum only certain columns in R?

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.


1 Answers

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
like image 64
Aaron left Stack Overflow Avatar answered Oct 11 '22 03:10

Aaron left Stack Overflow