A new vector based on a comparison of the elements of two other vectors "lagged"?

I have two vectors, subjectand target. I want to create a new vector based on a comparison between two existing vectors when comparing elements lagged. I solved it normally using the loop below, but I'm really curious if there is 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  }
   }
 }
+3
source share
2 answers

, . adjtarget , target. if :

lv <- but.last(subject) > but.last(target)
ind <- which(lv)

( x, , adjtarget), target :

x <- c(target[1], but.last(target))  # corresponds to the true branch of the `if`
x[ind+1] <- target[ind] - perweek    # corresponds to the false branch

,

x <- c(target[1], but.last(target) - (!lv)*perweek

, , , , .

+1

, , , ...

> (goal <- cbind(subject,target,adjtarget))

      subject target adjtarget
 [1,]     200    200       200
 [2,]     195    198       198
 [3,]     190    196       196
 [4,]     185    194       194
 [5,]     185    192       192
 [6,]     185    190       190
 [7,]     188    188       188
 [8,]     189    186       186
 [9,]     195    184       186
[10,]     200    182       186
[11,]     210    180       186
[12,]     210    178       186

, 186 adjtarget. (RHS), (LHS). , adjtarget 9 .

> y <- ifelse(subject > target, 1, 0) # matches TRUE case
> x <- target
> x[ind+1] <- target[ind]
> cbind(goal, x, y)
      subject target adjtarget   x y
 [1,]     200    200       200 200 0
 [2,]     195    198       198 198 0
 [3,]     190    196       196 196 0
 [4,]     185    194       194 194 0
 [5,]     185    192       192 192 0
 [6,]     185    190       190 190 0
 [7,]     188    188       188 188 0
 [8,]     189    186       186 186 1
 [9,]     195    184       186 186 1 # assigned correctly (?)
[10,]     200    182       186 184 1 # incorrect x; should be 186
[11,]     210    180       186 182 1 # incorrect x; should be 186
[12,]     210    178       186 180 1 # incorrect x; should be 186
+1

Source: https://habr.com/ru/post/1717172/


All Articles