Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement with multiple actions in R

Tags:

r

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.

like image 960
user1723765 Avatar asked Dec 31 '12 10:12

user1723765


People also ask

How do I write an if statement with multiple conditions in R?

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.

How does Ifelse work in R?

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.


1 Answers

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.

like image 146
Karsten W. Avatar answered Oct 13 '22 01:10

Karsten W.