Question

I was wondering if someone could help me calculate the first difference of a score by group. I know it should be a simple process but for some reason I'm having trouble doing it..... yikes

Here's an example data frame:

score <- c(10,30,14,20,6)

group <- c(rep(1001,2),rep(1005,3))

df <- data.frame(score,group)

> df 
  score group
1    10  1001
2    30  1001
3    14  1005
4    20  1005
5     6  1005

And here's the output I was looking for.

1   NA
2   20
3   NA  
4    6
5  -14

Thanks in advance.

Was it helpful?

Solution

This is one way using base R

df$diff <- unlist(by(df$score , list(df$group) , function(i) c(NA,diff(i))))

or

df$diff <- ave(df$score , df$group , FUN=function(i) c(NA,diff(i)))


or using data.table - this will be more efficient for larger data.frames

library(data.table)
dt <- data.table(df)
setkey(dt,group)
dt[,diff:=c(NA,diff(score)),by=group]

OTHER TIPS

Another approach using dplyr:

library(dplyr)

score <- c(10,30,14,20,6)
group <- c(rep(1001,2),rep(1005,3))
df <- data.frame(score,group)

df %>%
  group_by(group) %>%
  mutate(first_diff = score - lag(score))

Although not exactly what you are looking for, ddply within the 'plyr' package can be used ta calculate the differences by group

library(plyr)
out<-ddply(df,.(group),summarize,d1=diff(score,1))

This should do the trick, although it uses loops rather than an apply function, so there is likely room for improvement in code clarity/efficiency

out = numeric()
#out[1] will always be NA
out[1] = NA
for(i in 2:nrow(df)){
  if(df$group[i]==df$group[(i-1)]){
    out[i]=df$score[i]-df$score[(i-1)]
  } 
  else {
    out[i]=NA
  }
}
out
[1]  NA  20  NA   6 -14
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top