Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a function to groups within a data.frame in R

Tags:

dataframe

r

apply

I am trying to get the cumulative sum of a variable (v) for groups ("a" and "b") within a dataframe. How can I get the result at the bottom -- whose rows are even numbered properly -- into column cs of my dataframe?

> library(nlme)
> g <- factor(c("a","b","a","b","a","b","a","b","a","b","a","b"))
> v <- c(1,4,1,4,1,4,2,8,2,8,2,8)
> cs <- rep(0,12)
> d <- data.frame(g,v,cs)

> d
   g v cs
1  a 1 0
2  b 4 0
3  a 1 0
4  b 4 0
5  a 1 0
6  b 4 0
7  a 2 0
8  b 8 0
9  a 2 0
10 b 8 0
11 a 2 0
12 b 8 0

> r=gapply(d,FUN="cumsum",form=~g, which="v")
>r

$a     
   v   
1  1   
3  2   
5  3  
7  5  
9  7  
11 9  

$b    
    v 
2   4 
4   8 
6  12 
8  20 
10 28 
12 36 

> str(r)
List of 2
 $ a:'data.frame':  6 obs. of  1 variable:
  ..$ v: num [1:6] 1 2 3 5 7 9
 $ b:'data.frame':  6 obs. of  1 variable:
  ..$ v: num [1:6] 4 8 12 20 28 36

I guess I could figure out some laborious way to get the data from those dataframes into d$cs, but there's got to be some easy tweak I'm missing.

like image 600
exzackley Avatar asked May 18 '12 00:05

exzackley


People also ask

Is there a Groupby function in R?

Group_by() function belongs to the dplyr package in the R programming language, which groups the data frames. Group_by() function alone will not give any output. It should be followed by summarise() function with an appropriate action to perform. It works similar to GROUP BY in SQL and pivot table in excel.

What does apply () do in R?

apply() function apply() takes Data frame or matrix as an input and gives output in vector, list or array. Apply function in R is primarily used to avoid explicit uses of loop constructs. It is the most basic of all collections can be used over a matrice.

What does gather () do in R?

gather() collects a set of column names and places them into a single “key” column. It also collects the cells of those columns and places them into a single value column. You can use gather() to tidy table4 .

How do you split data into a group in R?

Split() is a built-in R function that divides a vector or data frame into groups according to the function's parameters. It takes a vector or data frame as an argument and divides the information into groups. The syntax for this function is as follows: split(x, f, drop = FALSE, ...)


1 Answers

split<- is a pretty weird beast

split(d$cs, d$g) <- lapply(split(d$v, d$g), cumsum)

leading to

> d
   g v cs
1  a 1  1
2  b 4  4
3  a 1  2
4  b 4  8
5  a 1  3
6  b 4 12
7  a 2  5
8  b 8 20
9  a 2  7
10 b 8 28
11 a 2  9
12 b 8 36
like image 75
Martin Morgan Avatar answered Oct 01 '22 18:10

Martin Morgan