jeudi 2 janvier 2020

How to delete from vector using ifelse condition in R

I have a vector a with values (1,2,3,4) and another vector b with values (1,1,0,1). Using the elements in b as a flag, I want to remove the vector elements from A at the same positions where 0 is found in element b.

  a <- c(1,2,3,4)
  b <- c(1,1,0,1)
     for(i in 1:length(b))
  {
    if(b[i] == 0)
    {
      a <- a[-i]
    }
  }

I get the desired output

a [1] 1 2 4

But using ifelse, I do not get the output as required.

    a <- c(1,2,3,4)
  b <- c(1,1,0,1)
    for(i in 1:length(b))
    {
      a <- ifelse(b[i] == 0,a[-i],a)
    }

Output:

a [1] 1

How to use ifelse in such situations?

Aucun commentaire:

Enregistrer un commentaire