I would like to write an if statement of the following form:
a=5
b=2
la<-function(a,b){
if(a>3){a}
else{b}
}
Now what I would like to do is not only have one action in the if statement but two, for example:
if(a>3){a and c<<-1000}
In this case to return 'a' and also write 1000 in variable 'c'
My question is how to put in multiple actions after the if statement.
Multiple Conditions To join two or more conditions into a single if statement, use logical operators viz. && (and), || (or) and ! (not). && (and) expression is True, if all the conditions are true.
In R, the ifelse() function is a shorthand vectorized alternative to the standard if...else statement. Most of the functions in R take a vector as input and return a vectorized output. Similarly, the vector equivalent of the traditional if...else block is the ifelse() function.
You should use the semicolon
if(a>3){c<-1000;a}
The last statement is the return value.
EDIT This works for multiple statements, too. You can omit the semicolon if you use line breaks, as in
if(a>3) {
c<-1000
d<-1500
a
} else {
e <- 2000
b
}
EDIT: this should work with ifelse
too. You would have to keep in mind that you are operating on a vector, though. Here is an example:
x <- sample(10, 100, replace=TRUE)
ifelse(x>3, {y <- 100; y+x}, x)
This adds 100 only to those elements of x that are larger than 3.
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