Reputation: 19
I would like to check three logical operators in R in the same line. That is I want Y1 to become 1 if x1 or x3 are smaller than 0.05 or x2 is smaller than 0.1
if (x1 <0.05 | x2 < 0.1 | x3 <0.05) {
Y1 <- 1
}
However, R gives me the following error message:
## Warning in if (x1 < 0.05 | x2 < 0.1 | x3 < 0.05) {: the condition has length > 1 and only the first element will be used
Why does R give me an error message? And if it is a problem how can I solve this without using two if-statements?
Upvotes: 0
Views: 434
Reputation: 415
Y1 <- as.numeric(x1 <0.05 | x2 < 0.1 | x3 <0.05)
Wrapping your statement with as.numeric
returns a 1
if TRUE
and a 0
if FALSE
Upvotes: 0
Reputation: 469
The ifelse()
function is what you are looking for probably
set.seed(1)
x1 <- runif(1000, 0,1)
x2 <- runif(1000, 0,1)
x3 <- runif(1000, 0,1)
y1 <- ifelse(x1 <0.05 | x2 < 0.1 | x3 <0.05, 1, NA)
y1[1:20]
[1] NA NA NA NA NA 1 NA NA NA NA 1 NA 1 NA 1 NA NA 1 NA NA
Upvotes: 1