noblabla
noblabla

Reputation: 113

Compute increase between rows for each same ID

A have a sorted data frame and I would like to compute the increase of x2 for each same ID. The input is already sorted in a certain manner:

ID    x2   x3  x4 
1    10   11   2  
2   100   12   4   
1    20   13  10 
7    24    3   1 
1    30   14   0   
3     6   15   1   
2    90   15   1 

I would like to get:

ID    x2   increase x3  x4 
1    10            11   2  
2   100            12   4   
1    20      +100% 13  10 
7    24             3   1 
1    30       +50% 14   0   
3     6            15   1   
2    90       -10% 15   1  

Upvotes: 1

Views: 42

Answers (1)

lukeA
lukeA

Reputation: 54247

You could do

df <- read.table(header=T, text="
ID    x2   x3  x4 
1    10   11   2  
2   100   12   4   
1    20   13  10 
7    24    3   1 
1    30   14   0   
3     6   15   1   
2    90   15   1")
df$increase <- ave(df$x2, df$ID, FUN = function(x) c(NA, diff(x)/head(x, -1))*100)
df$increase <- ifelse(is.na(df$increase), "", sprintf("%+.0f%%", df$increase))
df
#   ID  x2 x3 x4 increase
# 1  1  10 11  2         
# 2  2 100 12  4         
# 3  1  20 13 10    +100%
# 4  7  24  3  1         
# 5  1  30 14  0     +50%
# 6  3   6 15  1         
# 7  2  90 15  1     -10%

Upvotes: 2

Related Questions