I have two vectors, "subject" and "target". I want to create a new vector based on comparisons between the two existing vectors, with elements being compared "lagged". I've solved this okay using the loop below, but I'm essentially wondering whether there's a more elegant solution using apply?
subject <- c(200,195,190,185,185,185,188,189,195,200,210,210)
target <- c(subject[1],subject[1]-cumsum(rep(perweek,length(subject)-1)))
adjtarget <- target
for (i in 1:(length(subject)-1)) {
if (subject[i] > adjtarget[i]) {
adjtarget[i+1] <- adjtarget[i]
} else {
adjtarget[i+1] <- adjtarget[i]-perweek }
}
}
(I hope this code is still correct. Frankly, I find the way of entering code here at stackoverflow.com, with only indentation to go by, bewildering)