user3022875
user3022875

Reputation: 9018

calculate return on columns for multiple groups

I have a data frame

 data.frame(quarter= c(1,2,3), group1 = c(1,2,3), group2 = c(6,8,10))

what's the best way to produce the return by quarter so the results are

quarter  group1  group 2
2         1.0     .333
3          .5        .25

where the return calculation is (Current value - PRevious) /previous so for quarter 3 group 1 (3-2)/2 =.5

Upvotes: 0

Views: 37

Answers (2)

akrun
akrun

Reputation: 887551

Or we can use mutate_each from dplyr

library(dplyr)
df %>%
   mutate_each(funs(c(NA, diff(.))/lag(.)), group1:group2) %>% 
   na.omit
#   quarter group1    group2
#2       2    1.0 0.3333333
#3       3    0.5 0.2500000

Upvotes: 0

Jilber Urbina
Jilber Urbina

Reputation: 61204

Since your data is not a time series object, you can use apply to operate on your data.frame:

> data.frame(quarter=df[-1,1], apply(df[,-1], 2, function(x) diff(x)/x[-length(x)]) )
  quarter group1    group2
1       2    1.0 0.3333333
2       3    0.5 0.2500000

Upvotes: 1

Related Questions