My data roughly appears like the following and I want to calculate a variable for each participant (v001
) with the difference between the last two available measurements (from lnslope1
to lnslope9
). Every subject has at least two measurements.
My question is:
How can I do this in R? I have read about the diff
function but I am not sure if it can be used here. Do I have to restructure the data in a long format to do this calculation? Here is the data:
structure(list(v001 = c(10002, 10004, 10005, 10006, 10007, 10011,
10012, 10018), lnslope1 = c(NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_), lnslope2 = c(NA, NA,
0.313091787977149, 0.800960043896479, NA, NA, 0, 0.246092484299754
), lnslope3 = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_), lnslope4 = c(NA, 0.218445030532656,
NA, NA, NA, NA, 0.505548566665147, NA), lnslope5 = c(0.0507723253734231,
NA, -0.0361572285993463, NA, -0.133531392624523, -0.0824189464154196,
NA, -0.186877373329815), lnslope6 = c(0.606135803570316, NA,
NA, NA, -0.0408887702539783, 0.304548524450922, NA, 0.099090902644231
), lnslope7 = c(0.192160005794242, NA, NA, 1.37147927533475,
NA, 0.485507815781701, NA, 0.0307716586667537), lnslope8 = c(0.10951852580649,
NA, NA, 1.53234783071453, 0.145860850410924, 0.604821224703469,
NA, 0.0692660582117757), lnslope9 = c(0.374693449441411, NA,
NA, 0.996237878364571, NA, 0.852777326151829, NA, 0.0299842570512681
)), .Names = c("v001", "lnslope1", "lnslope2", "lnslope3", "lnslope4",
"lnslope5", "lnslope6", "lnslope7", "lnslope8", "lnslope9"), row.names = c(NA,
8L), class = "data.frame")