I have the following dataset. I want to create a column that checks for rows where only A has a positive number but the rest are 0s (ifelse assignment 1 or 0). Attached is the code below. I expect the columns to have all 0s except a "1" in the last row. Currently, I am getting a "0" for the rows. Any suggestions?
set.seed(111)
A <- rnorm(10,10,2)
B <- c(23,0,0,0,1,2,0,1,2,0)
C <- c(1,1,23,0,0,0,1,2,0,0)
D <- c(0,1,1,23,0,0,0,1,2,0)
df <- data.frame(A,B,C,D)
df$A.only <- ifelse(df$A > 0 && df$B == 0 && df$C == 0 && df$D == 0, 1, 0)
CodePudding user response:
Potential duplicate: Boolean operators && and ||
If you use "&" instead of "&&" your command works as expected, e.g.
set.seed(111)
A <- rnorm(10,10,2)
B <- c(23,0,0,0,1,2,0,1,2,0)
C <- c(1,1,23,0,0,0,1,2,0,0)
D <- c(0,1,1,23,0,0,0,1,2,0)
df <- data.frame(A,B,C,D)
df$A.only <- ifelse(df$A > 0 & df$B == 0 & df$C == 0 & df$D == 0, 1, 0)
df
#> A B C D A.only
#> 1 10.470441 23 1 0 0
#> 2 9.338528 0 1 1 0
#> 3 9.376752 0 23 1 0
#> 4 5.395309 0 0 23 0
#> 5 9.658248 1 0 0 0
#> 6 10.280556 2 0 0 0
#> 7 7.005147 0 1 0 0
#> 8 7.979623 1 2 1 0
#> 9 8.103049 2 0 2 0
#> 10 9.012076 0 0 0 1
Created on 2022-04-04 by the reprex package (v2.0.1)