Friday, 15 May 2015

r - Calculating change from baseline with data in long format -



r - Calculating change from baseline with data in long format -

here little reproducible illustration of data:

> mydata <- structure(list(subject = c(1, 1, 1, 2, 2, 2), time = c(0, 1, 2, 0, 1, 2), measure = c(10, 12, 8, 7, 0, 0)), .names = c("subject", "time", "measure"), row.names = c(na, -6l), class = "data.frame") > mydata subject time measure 1 0 10 1 1 12 1 2 8 2 0 7 2 1 0 2 2 0

i generate new variable "change baseline". is, like

subject time measure alter 1 0 10 0 1 1 12 2 1 2 8 -2 2 0 7 0 2 1 0 -7 2 2 0 -7

is there easy way this, other looping through records programatically or reshaping wide format first ?

what about:

mydata$change <- do.call("c", with(mydata, lapply(split(measure, subject), function(x) x - x[1])))

alternatively utilize ave function:

with(mydata, ave(measure, subject, fun=function(x) x - x[1])) # [1] 0 2 -2 0 -7 -7

or

within(mydata, alter <- ave(measure, subject, fun=function(x) x - x[1])) # subject time measure alter # 1 1 0 10 0 # 2 1 1 12 2 # 3 1 2 8 -2 # 4 2 0 7 0 # 5 2 1 0 -7 # 6 2 2 0 -7

r

No comments:

Post a Comment