Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate a percentage from the start of an intervention in R

Tags:

r

dplyr

I have a data frame that has vertical jump power for a group of athletes over an 8 week tim period. One athlete only completed seven weeks. I want to calculate a new variable called "percent.change" which calculates the percent difference from the first week for each of the weeks through the study period. I have been trying to use dplyr to figure this out but I'm stuck. I'm wondering if anyone out there has a straightforward solution.

The data frame is called weeklyPower. A sample of weeklyPower is below:

athlt week     power
E      1       25.20015
E      2       25.54569
E      3       24.52463
E      4       24.88044
E      5       25.11421
E      6       25.86154
E      7       26.08613
E      8       25.90775
K      1       29.74277
K      2       28.80131
K      3       28.96818
K      4       29.62439
K      5       29.98119
K      6       29.11570
K      7       29.96380
T      1       25.02413
T      2       23.75867
T      3       25.25716
T      4       24.73285
T      5       27.02891
T      6       25.60140
T      7       25.64665
T      8       24.38937 

Thank you very much for any thoughts.

Matt

like image 630
Matt Jordan Avatar asked Apr 27 '15 02:04

Matt Jordan


1 Answers

Using dplyr you could do:

df %>% 
  group_by(athlt) %>% 
  arrange(week) %>% 
  mutate(cp = power / first(power) * 100)

Which gives:

#Source: local data frame [23 x 4]
#Groups: athlt

#   athlt week    power        cp
#1      E    1 25.20015 100.00000
#2      E    2 25.54569 101.37118
#3      E    3 24.52463  97.31938
#4      E    4 24.88044  98.73132
#5      E    5 25.11421  99.65897
#6      E    6 25.86154 102.62455
#7      E    7 26.08613 103.51577
#8      E    8 25.90775 102.80792
#9      K    1 29.74277 100.00000
#10     K    2 28.80131  96.83466

Or another option:

df %>% 
  group_by(athlt) %>% 
  mutate(cp = power / power[which.min(week)] * 100)
like image 137
Steven Beaupré Avatar answered Oct 04 '22 19:10

Steven Beaupré