This code is a complex if.
I write this code because I want to use the flow control to decide whether the user can eat the cake or not.
The variables a, b, c, d are some indexes that the user will put in.
In this place, I have already set these indexes.
Based on the indexes, the nested if will give some responses.
a <- 1 ; b <- 2 ; c <- 3 ; d <- 3
index <- sum(a, b, c, d)
if(index > 11){print("enjoy the cake right now!")
}else{
if(b == 1 | c == 1){"You don't have the right to eat cake."
}else{
ifelse(b == 3, "go to ATM and take money right now",
ifelse(b == 2, "use the budget of tomorrow first",print("") )
)
print("bb")
ifelse(c == 4, "run to the cake store and burn some calores ",
ifelse(c == 3,"ride youbike to the cake store",
ifelse(c == 2, "ride youbike to the cake store",print(""))))
print("aa")
}
}
My expectation is:
[1] "use the budget of tomorrow first"
[1] "bb"
[1] "ride youbike to the cake store"
[1] "aa"
But the result is:
[1] "bb"
[1] "aa"
Why the R program didn't run the "ifelse" part and just printed "bb", "aa"?
Is this because the "else" can't include "ifelse"?
You can have multiple ifelse in else but it doesn't print the string here is because ifelse returns the value and does not print them by default. You need to explicitly print them. If you add print around those strings in ifelse it would work. However, as you have scalar input to compare here you can use if/else instead of ifelse which is usually used for vector inputs.
if(index > 11) {
print("enjoy the cake right now!")
} else {
if(b == 1 | c == 1) {print("You don't have the right to eat cake.")
} else{
if(b == 3) print("go to ATM and take money right now")
else if(b == 2) print("use the budget of tomorrow first") else print("")
print("bb")
if(c == 4) print("run to the cake store and burn some calores ")
else if (c == 3) print("ride youbike to the cake store")
else if(c == 2) print("ride youbike to the cake store") else print("")
print("aa")
}
}
#[1] "use the budget of tomorrow first"
#[1] "bb"
#[1] "ride youbike to the cake store"
#[1] "aa"
Related
starting to get familiar with R. can't get why this simple chunk doesn't work
want to do it particularly using 'break'
prime.check <- function(num) {
for (del in 2:(num-1)) {
if (num %% del == 0) {
break
}
print(paste(num, 'is not prime'))
}
}
Your function is going to print every time in the loop, which is not really what is desired: you should be finishing the loop and then determining what to print. I suggest assuming it is a prime and then if you break, then know that it is not a prime.
See
prime.check <- function(num) {
isprime <- TRUE
for (del in 2:(num-1)) {
if (num %% del == 0) {
isprime <- FALSE
break
}
}
isnot <- if (isprime) "is" else "is not"
print(paste(num, isnot, "prime"))
invisible(isprime)
}
prime.check(7)
# [1] "7 is prime"
prime.check(6)
# [1] "6 is not prime"
FYI, the invisible(isprime) allows you to use this function elsewhere, such as if (prime.check(8)) { do_something(); }, whereas with the print alone you couldn't do that. Completely ancillary from your original request.
The condition inside the for loop checks if num is divisible by del without a reminder, e.g. it is not prime.
In addition, use return instead of break to finalize a function.
prime.check <- function(num) {
if(num == 2) return("prime")
for (del in 2:(num-1)) {
if (num %% del == 0) {
return("not prime")
}
}
return("prime")
}
prime.check(2)
#> [1] "prime"
prime.check(3)
#> [1] "prime"
prime.check(4)
#> [1] "not prime"
prime.check(9)
#> [1] "not prime"
prime.check(10)
#> [1] "not prime"
Here is another option with no loop:
prime.check <- function(x){
if(sum(x %% 1:x == 0) == 2) return(paste(x, 'is prime'))
return(paste(x, 'is not prime'))
}
prime.check(2)
#> [1] "2 is prime"
prime.check(3)
#> [1] "3 is prime"
prime.check(4)
#> [1] "4 is not prime"
prime.check(9)
#> [1] "9 is not prime"
prime.check(10)
#> [1] "10 is not prime"
You can do this without a loop:
prime.check <- function(num) {
if (num==2) return("2 is prime")
if (all(num %% seq(2, num/2) > 0)) {
return(paste(num, "is prime"))
} else return(paste(num, "is not prime"))
}
Is there a way to check the color of this diagram without using too much if?
Not like this:
if(x == "b" && y == "b"){ return "red";}
if(x == "b" && y == "e1" || x == "b" && y == "e2" .....){ return "green";}
........
I think there must be a way to simple calculate the result with given values for the characters, but I can't find it.
Something like checking x+y=z or x*y=z. Where z can be one of three numbers.
The language doesn't matter.
Thanks
I'd recommend targeting the red diagonal and green column, picking off individual cases and then returning yellow:
if x == "i"{ return "yellow"}
if y == "i"{ return "yellow"}
if x[0] == y[0]{ return "green"}
/*
target remaining green cases
*/
return "yellow"
This is a very common question: 1, 2, 3, 4, 5, and still I cannot find even an answer to my problem.
If a == 1, then do X.
If a == 0, then do Y.
If a == 0 and b == 1, then do Z.
Just to explain: the if else statements has to do Y if a==0 no matter the value of b. But if b == 1 and a == 0, Z will do additional changes to those already done by Y.
My current code and its error:
if (a == 1){
X
} else if(a == 0){
Y
} else if (a == 0 & b == 1){
Z}
Error in !criterion : invalid argument type
An else only happens if a previous if hasn't happened.
When you say
But if b == 1 and a == 0, Z will do additional changes to those already done by Y
Then you have two options:
## Option 1: nest Z inside Y
if (a == 1){
X
} else if(a == 0){
Y
if (b == 1){
Z
}
}
## Option 2: just use `if` again (not `else if`):
if (a == 1) {
X
} else if(a == 0) {
Y
}
if (a == 0 & b == 1) {
Z
}
Really, you don't need any else here at all.
## This will work just as well
## (assuming that `X` can't change the value of a from 1 to 0
if (a == 1) {
X
}
if (a == 0) {
Y
if (b == 1){
Z
}
}
Typically else is needed when you want to have a "final" action that is done only if none of the previous if options were used, for example:
# try to guess my number between 1 and 10
if (your_guess == 8) {
print("Congratulations, you guessed my number!")
} else if (your_guess == 7 | your_guess = 9) {
print("Close, but not quite")
} else {
print("Wrong. Not even close!")
}
In the above, else is useful because I don't want to have enumerate all the other possible guesses (or even bad inputs) that a user might enter. If they guess 8, they win. If they guess 7 or 9, I tell them they were close. Anything else, no matter what it is, I just say "wrong".
Note: this is true for programming languages in general. It is not unique to R.
However, since this is in the R tag, I should mention that R has if{}else{} and ifelse(), and they are different.
if{} (and optionally else{}) evaluates a single condition, and you can run code to do anything in {} depending on that condition.
ifelse() is a vectorized function, it's arguments are test, yes, no. The test evaluates to a boolean vector of TRUE and FALSE values. The yes and no arguments must be vectors of the same length as test. The result will be a vector of the same length as test, with the corresponding values of yes (when test is TRUE) and no (when test is FALSE).
I believe you want to include Z in the second condition like this:
if (a == 1){X}
else if(a == 0){
Y
if (b == 1){Z}
}
I'm trying to use multiple actions in if statement. For example:
x <- 1
if (x == 1) {
paste("First")
1*1 #multiple actions
} else if (x == 2) {
paste("Second")
2*2 } else {("Nothing")
}
[1] 1 #what I'm getting
[2] "First"
1 #what I want to get
In this case only the second part of the expressions was printed to the console.
Any ideas how can I run all actions between if and else if ?
All statements are running as intended. The value of a statement is only printed to the console if all these conditions are true:
The value isn't saved to a variable
The value isn't invisible
It's the result of the last statement in an expression
R is running in interactive mode
The reason things sometimes print is to help people interactively exploring data in the command line. Instead of type print(x), they can save a few keystrokes by just typing x. In summary, use print if you want to be sure it's printed:
x <- 1
if (x == 1) {
print("First")
print(1*1)
} else if (x == 2) {
print("Second")
print(2*2)
} else {
invisible("Nothing")
}
# [1] "First"
# [1] 1
You can use print or cat:
getResult <- function(x = 1) {
if (x == 1) {
cat("First", 1 * 1, "\n")
} else if (x == 2) {
print("Second")
print(2 * 2)
} else {
cat("Nothing\n")
}
}
getResult()
# First 1
getResult(2)
# [1] "Second"
# [1] 4
I can't seem to find the resource I need. What does && do in a code that is comparing variables to determine if they are true? If there is a link with a list of the symbol comparisons that would be greatly appreciated.
example: Expresssion 1: r = !z && (x % 2);
In most programming languages that use &&, it's the boolean "and" operator. For example, the pseudocode if (x && y) means "if x is true and y is true."
In the example you gave, it's not clear what language you're using, but
r = !z && (x % 2);
probably means this:
r = (not z) and (x mod 2)
= (z is not true) and (x mod 2 is true)
= (z is not true) and (x mod 2 is not zero)
= (z is not true) and (x is odd)
In most programming languages, the operator && is the logical AND operator. It connects to boolean expressions and returns true only when both sides are true.
Here is an example:
int var1 = 0;
int var2 = 1;
if (var1 == 0 && var2 == 0) {
// This won't get executed.
} else if (var1 == 0 && var2 == 1) {
// This piece will, however.
}
Although var1 == 0 evaluates to true, var2 is not equals to 0. Therefore, because we are using the && operator, the program won't go inside the first block.
Another operator you will see ofter is || representing the OR. It will evaluate true if at least one of the two statements are true. In the code example from above, using the OR operator would look like this:
int var1 = 0;
int var2 = 1;
if (var1 == 0 || var2 == 0) {
// This will get executed.
}
I hope you now understand what these do and how to use them!
PS: Some languages have the same functionality, but are using other keywords. Python, e.g. has the keyword and instead of &&.
It is the logical AND operator
(&&) returns the boolean value true if both operands are true and returns false otherwise.
boolean a=true;
boolean b=true;
if(a && b){
System.out.println("Both are true"); // Both condition are satisfied
}
Output
Both are true
The exact answer to your question depends on the which language your are coding in. In R, the & operator does the AND operation pairwise over two vectors, as in:
c(T,F,T,F) & c(T,T,F,F)
#> TRUE FALSE FALSE FALSE
whereas the && operator operated only on the first element of each vector, as in:
c(T,F,T,F) && c(T,T,F,F)
#> TRUE
The OR operators (| and ||) behave similarly. Different languages will have different meanings for these operators.
In C && works like a logical and, but it only operates on bool types which are true unless they are 0.
In contrast, & is a bitwise and, which returns the bits that are the same.
Ie. 1 && 2 and 1 && 3 are true.
But 1 & 2 is false and 1 & 3 is true.
Let's imagine the situation:
a = 1
b = 2
if a = 1 && b = 2
return "a is 1 and b is 2"
if a = 1 && b = 3
return "a is 1 and b is 3"
In this situation, because a equals 1 AND b = 2, the top if block would return true and "a is 1 and b is 2" would be printed. However, in the second if block, a = 1, but b does not equal 3, so because only one statement is true, the second result would not be printed. && Is the exact same as just saying and, "if a is 1 and b is 1".