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
Not sure why
Eggs
are important here ;)now with
n=2
i.e. first two rows:The expression
[df1[, "Gr"]<=n]
creates a logical vector to subset the elements indf1[, "x"]
beforesum
ming them.Also, it appears your
Group.1
is the same as the row no. If so this may be simpler:or to get all at once
Assuming your data is in
mydata
:If the sums you want are always cumulative, there's a function for that,
cumsum
. It works like this.In this case you might want something like
You could use the
by
function.For instance, given the following data.frame:
You can do this: