Calculate new values in R time series -


i have dataset of type

id      variable       value 200         b/l         81.3     200         wk2         6.1 200         wk4         2.0 200         wk8         2.2 201         b/l         123.3 201         wk2         89.3 201         wk4         72.4     201         wk8         55.8 

i'd add rows change in variable between timepoints eg

id      variable       value 200         b/l         81.3     200         deltab/l    na 200         wk2         6.1 200         deltawk2    -75.2 200         wk4         2.0 200         deltawk4    -4.1 200         wk8         2.2 200         deltawk8    0.2 201         b/l         123.3 201         deltab/l    na 201         wk2         89.3 201         deltawk2    -34 201         wk4         72.4     201         deltawk4    -16.9 201         wk8         55.8 201         deltawk8    -16.6 

any idea on how efficiently?

the variable column seems ordered factor, fortunately order coincides alphabetical order. creating new column delta seems idea, that's not you've asked for. code below produces output describe.

library(tidyverse) df <- data.frame(   id = c(200,200,200,200,201,201,201,201),   variable = c('b/l', 'wk2', 'wk4', 'wk8', 'b/l', 'wk2', 'wk4', 'wk8'),   value = c(81.3, 6.1, 2.0, 2.2, 123.3, 89.3, 72.4, 55.8))  group_by(df, id) %>%   do({mutate(., value = c(na, diff(value)),              variable = paste0(unique(variable), 'delta'))}) %>%   bind_rows(df) %>%   arrange(id, variable) 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -