Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IF statement with OR condition does not work for a dataframe in R

I want to add new column to my dataframe that only has two values ,1 and 0. 1 if either of the x, y, and z columns have an instance of 1, and 0 otherwise. For instance, with this rule, all but rows 6 and 9 have new column value as 1. But, my code does not work in this way.

I would appreciate if someone could help me on this.

set.seed(1)
x <- sample(1:3, 10, replace = TRUE)
y <- sample(1:3, 10, replace = TRUE)
z <- sample(1:3, 10, replace = TRUE)
df <- data.frame(x,y,z)

for (i in 1:nrow(df)){
  if ((df$x[i] == 1)== TRUE | (df$y[i] == 1) == TRUE | (df$z[i] == 1) == TRUE){
    df$new <- 1
  }
  else{
    df$new <- 0
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’ll need indices on your new-variable. Note though that there are faster ways to achieve this end using the apply-family instead of a loop (I am sure other’s will post these).

for (i in 1:nrow(df)){
  if ((df$x[i] == 1) | (df$y[i] == 1) | (df$z[i] == 1)){
    df$new[i] <- 1
  }
  else{
    df$new[i] <- 0
  }
}

We could even shorten it to, converting the logical to numeric:

for (i in 1:nrow(df)){
  df$new[i] <- +((df$x[i] == 1) | (df$y[i] == 1) | (df$z[i] == 1))
}

Output:

df
   x y z new
1  1 3 3   1
2  3 1 1   1
3  1 1 1   1
4  2 1 1   1
5  1 2 1   1
6  3 2 2   0
7  3 2 1   1
8  2 2 1   1
9  2 3 2   0
10 3 1 2   1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading