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"
}
Some alternatives to the if-else statement in C++ include loops, the switch statement, and structuring your program to not require branching.
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.
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 .
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.
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.)
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
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