I have read many of the if statement posts but have not been able to find an answer to my simple problem. I would like to create a new column in the data frame 'tester' based on a multiple condition if statement.
tester<- as.data.frame(matrix(data=c(seq(1,300,by=1.5)), ncol=4))
if (tester$V3> 200 && tester$V4>250){tester[,5] <- "one"} else tester$V5 <-NA
This gives me NAs for the entire column even though the last 17 rows are TRUE for both cases and should be "one". What is happening here? Thank you for your help!
Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.
Test Multiple Conditions With the || Operator There are times you'll want to perform an action if either of the two possible conditions is true. In this video, you'll use the logical OR (|| ) operator to test multiple conditions. Try to keep your conditional statements short and precise.
We can also write multiple conditions inside a single if statement with the help of the logical operators && and | | . The && operators will evaluate if one condition AND another is true. Both must be true before the code in the code block will execute.
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With