I'm trying to calculate percent change in R with each of the time points included in the column label (table below). I have dplyr loaded and my dataset was loaded in R and I named it data. Below is the code I'm using but it's not calculating correctly. I want to create a new dataframe called data_per_chg which contains the percent change from "v1" each variable from. For instance, for wbc variable, I would like to calculate percent change of wbc.v1 from wbc.v1, wbc.v2 from wbc.v1, wbc.v3 from wbc.v1, etc, and do that for all the remaining variables in my dataset. I'm assuming I can probably use a loop to easily do this but I'm pretty new to R so I'm not quite sure how proceed. Any guidance will be greatly appreciated.
| id | wbc.v1 | wbc.v2 | wbc.v3 | rbc.v1 | rbc.v2 | rbc.v3 | hct.v1 | hct.v2 | hct.v3 |
|---|---|---|---|---|---|---|---|---|---|
| a1 | 23 | 63 | 30 | 23 | 56 | 90 | 13 | 89 | 47 |
| a2 | 81 | 45 | 46 | N/A | 18 | 78 | 14 | 45 | 22 |
| a3 | NA | 27 | 14 | 29 | 67 | 46 | 37 | 34 | 33 |
data_per_chg<-data%>%
group_by(id%>%
arrange(id)%>%
mutate(change=(wbc.v2-wbc.v1)/(wbc.v1))
data_per_chg