Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for if else

Tags:

r

if-statement

What is the shortest way to express the folowing decission rule

df<-data.frame(a=LETTERS[1:5],b=1:5)
index<-df[,"a"]=="F"
if(any(index)){
  df$new<-"A"
}else{
  df$new<-"B"
}
like image 200
Klaus Avatar asked Aug 23 '13 10:08

Klaus


People also ask

What is the alternative of if-else?

Some alternatives to the if-else statement in C++ include loops, the switch statement, and structuring your program to not require branching.

How do I shorten if-else in JavaScript?

Use the ternary operator to use a shorthand for an if else statement. The ternary operator starts with a condition that is followed by a question mark ? , then a value to return if the condition is truthy, a colon : , and a value to return if the condition is falsy.

What is the else if keyword?

elseif , as its name suggests, is a combination of if and else . Like else , it extends an if statement to execute a different statement in case the original if expression evaluates to false .

How do you write the if-else condition?

Conditional Statements Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.


2 Answers

Shortest is

df$new=c("B","A")[1+any(df$a=="F")]

More elegant is:

df$new <- if (any(df$a == "F")) "A" else "B"

or

df <- transform(df, new = if (any(a == "F")) "A" else "B")

The ifelse operator was suggested twice, but I would reserve it for a different type of operation:

df$new <- ifelse(df$a == "F", "A", "B")

would put a A or a B on every row depending on the value of a in that row only (which is not what your code is currently doing.)

like image 129
flodel Avatar answered Oct 22 '22 21:10

flodel


Maybe using the vectorized version ifelse

> df$new <- ifelse(any(df[,"a"]=="F"), "A", "B")
> df
  a b new
1 A 1   B
2 B 2   B
3 C 3   B
4 D 4   B
5 E 5   B
like image 31
Jilber Urbina Avatar answered Oct 22 '22 21:10

Jilber Urbina