Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store variable with multiple condition in for loop until condition is met in R

Tags:

loops

for-loop

r

(I know for loops aren't the preferred choice in R but this was the best I could come up with)

I'm trying to loop through a vector and return the vector value once a condition is met.

Once the next condition is met I would like to drop the variable.

So far I've gotten to the following:

df = c(1:10)

sig = function (df) {

  pos = integer(10)

  for (i in 1:10) {

    if (df[i] > 3 ) { # Once df[i] is bigger than 3 store the value of df[i]
      pos[i] = df[i]
    } 
    else if(df[i] < 7 ){ # Keep value of df[i] until next condition is met
      pos[i] = pos[i - 1]
    } 
    else{pos[i] = 0} # set the value back to 0
  }

  reclass(pos,df)
}

sig(df)

I'm getting the following error Error in pos[i] <- pos[i - 1] : replacement has length zero

The answer should look like the following:

df  sig
1    0
2    0
3    0
4    4
5    4
6    4
7    0
8    0
9    0
10   0

Any ideas?

like image 941
Davis Avatar asked Nov 30 '25 16:11

Davis


1 Answers

Another way to achieve your output:

pos = integer(10)
pos[df>3 & df<7]<-df[which.max(df>3 & df<7)]
cbind(df,pos)
      df pos
 [1,]  1   0
 [2,]  2   0
 [3,]  3   0
 [4,]  4   4
 [5,]  5   4
 [6,]  6   4
 [7,]  7   0
 [8,]  8   0
 [9,]  9   0
[10,] 10   0

About your problem

i start from 1, in the for loop you have pos[i-1], so pos[0] but the list start from 1.

Try this:

sig = function (df) {

  pos = integer(10)

  for (i in 1:10) {

    if (df[i] > 3 ) { # Once df[i] is bigger than 3 store the value of df[i]
      pos[i] = df[i]
    } 
    else if(df[i] < 7 ){ # Keep value of df[i] until next condition is met
      if(i>1) {
        pos[i] = pos[i - 1] 
      } else

      {
        pos[i]=0
      }
    } 
    else{pos[i] = 0} # set the value back to 0
  }

  return(cbind(df,pos))
}

return instruction added

Your output:

sig(df)
      df pos
 [1,]  1   0
 [2,]  2   0
 [3,]  3   0
 [4,]  4   4
 [5,]  5   5
 [6,]  6   6
 [7,]  7   7
 [8,]  8   8
 [9,]  9   9
[10,] 10  10

The output is different from the one aspected, so you have to find other errors in your logic inside the for loop.

like image 144
Terru_theTerror Avatar answered Dec 02 '25 06:12

Terru_theTerror



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!