Ladder if else with multiple statements in each - r

I want to do this ladder if else with multiple statements within each condition, however, it runs to the two following errors:
Error: unexpected symbol in: and
Error: unexpected '}' in "}".
It seems that it is not possible to have more than one statement within each condition, but shouldn't be the case. right?
if (condition 1){
results[i,3] <- 1
results[i,4] <- 1
}
else if (condition 2){
results[i,1] <- 1
results[i,2] <- 1
}
else
results[i,1:4] <- 0

The way R works is that it reads a line, iterpretes it, executes it if possible, reads next line
After in this snippet
if (condition 1){
results[i,3] <- 1
results[i,4] <- 1
}
the last line is read, R thinks that the if body is finished and executes it.
Afterwards it reads else and cannot put the else in an context with an if (because that was already processed)
What you instead want is to do is put a else in the same line as the closed curly brackets so that R knows it needs to read further before execution.
if (condition 1){
results[i,3] <- 1
results[i,4] <- 1
} else if (condition 2){
results[i,1] <- 1
results[i,2] <- 1
} else {
results[i,1:4] <- 0
}

This works, and the former didn't work because else started at a new line, not immediately after closing curly bracket.
if (condition 1){
results[i,3] <- 1
results[i,4] <- 1
} else if (condition 2){
results[i,1] <- 1
results[i,2] <- 1
} else {
results[i,1:4] <- 0
}

Related

R loop checking condition X times and break if not met

I'd like to create kind of dependency between R and database and for that I'm trying to create a loop which is checking if a date in one column from a database is equal to today's date, if yes then run main statement, if not wait 5mins and try again (max 24 times) then break. I'm stucked with the latter, if someone could advice that would be helpful, thanks!
if(lubridate::date(table$db_date) == Sys.Date()){
print(1)
} else {
Sys.sleep(300)
# and repeat the loop 24 times until statement is TRUE, if not then break
}
If you have an upper limit for the number of iterations, you should use a for loop:
for (i in seq_len(24)) {
if(lubridate::date(table$db_date) == Sys.Date()){
print(1)
break
} else {
Sys.sleep(300)
}
}
Very primitive but maybe something like this:
i=1 # establish global variable
while (T) {
if(lubridate::date(table$db_date) == Sys.Date()){
print(1)
# break
}
if(i < 24 & lubridate::date(table$db_date) != Sys.Date()) { # check both statements
i <<- i+1 # update global variable
Sys.sleep(0.1) # and repeat the loop 24 times until statement is TRUE, if not then break
}
else{break}
}

Does the line break between "}" and "else" really matters?

It is clearly that the documentation of R clearly goes against having a break line between "}" and "else". However, it is odd that the first piece of codes works but the second one does not work (syntax error)
First program
x = 1
stupid_function = function(x){
if(x != 1){
print("haha")
}
else if( x == 1){
print("hihi")
}
}
stupid_function(x)
[1] "hihi"
Second program
x = 1
if(x != 1){
print("haha")
}
else if( x == 1){
print("hihi")
}
Error in source("~/.active-rstudio-document", echo = TRUE) :
~/.active-rstudio-document:6:3: unexpected 'else'
5: }
6: else
In the second program it sees a line at a time as it is typed in so at the point that the line with the } is typed in it cannot know that there will be further lines with an else so it assumes the statement is finished.
In the first case it can see all the code before it is run because it can see all the code in the function so it knows that the } has not finished the statement.
This line of argument works for an if/else but does not work in general. For example, this will produce an error when the function is
defined.
f <- function(x) {
x
* 2
}
Note that the if else need not be in a function for it to work. It just need to be in a continuous form or in a way to be expressed as a continuous block of code. One way is being in a function. The other is to write it in one line, or even ensure that there is no line break between the if block and the else block:
x <- 1
if(x != 1) print('haha') else print('hihi')
[1] "hihi"
More blocks of statements:
x <- 1
if(x != 1){
print("haha")
} else if( x == 1){ # Note how else begins immediatley after }
print("hihi")
}
[1] "hihi"
Note that you need to know when to put the line breaks whether in a function or outside of a function. Otherwise the code might fail or even give incorrect results.
Using subtraction:
x <- 1
x -
2
[1] -1
x <- 1
x
- 2
[1] -2
You need to know when/where to have the line breaks. Its always safe to have else follow the closing brace } of the previous if statement. ie:
if(...){
....
} else if(...){
....
} else {
...
}

Return result from multiple if statements

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

Multiple conditions in if statements in R

I am trying to cut down a list of gene names that I have been given. I'm trying to eliminate any repetitive names that may be present but I keep getting an error when running my code:
counter=0
i=0
j=0
geneNamesRevised=array(dim=length(geneNames))
for (i in 0:length(geneNamesRevised))
geneNamesRevised[i]=""
geneNamesRevised
for (i in 1:length(geneNames))
for (j in 1:length(geneNamesRevised))
if (geneNames[i]==geneNamesRevised[j])
{
break
}
else if ((j==length(geneNamesRevised)-1) &&
(geneNames[i]!=geneNamesRevised[j]))
{
geneNamesRevised[counter]=geneNames[i]
counter++
}
The error message is a repetitive string of :
the condition has length > 1 and only the first element will be usedthe condition has length > 1 and only the first element will be usedthe condition has length > 1 and only the first element will be used
and this error message is for the last "else if" statement that has the '&&'.
Thank you!
Why not just
geneNamesRevised <- unique( geneNames )
... which returns a shortened list. There is also a duplicated function that can be used to remove duplicates when negated.
There are a few problems in your code.
1) The else is incorrectly specified - or not :) thanks #Mohsen_Fatemi
2) & is usually what you need rather than &&
3) counter++ isn't R
Copy the code below and see if it runs
for (i in 1:length(geneNames)){
for (j in 1:length(geneNamesRevised)){
if (geneNames[i]==geneNamesRevised[j])
{
break
} else {
if ((j==length(geneNamesRevised)-1) & (geneNames[i]!=geneNamesRevised[j]))
{
geneNamesRevised[counter]=geneNames[i]
counter <- counter + 1
}
}
}
}
Edit
4) also you were missing braces for your fors
use & instead of && ,
else if ((j==length(geneNamesRevised)-1) & (geneNames[i]!=geneNamesRevised[j]))

if statement in R can only have one line?

I was trying a tiny code with if statement, although it is very simple,but there is something I really confused here is the code
n<-857
while(n!=1){
if(n<=0)
print("please input a positive integer")
else if(n%%2==0)
n<-n/2
print(n)
else
n<-3*n+1
print(n)
}
as we see above,when running this code in R, there comes the error,but if I change the if statement like this
if(n<=0)
print("please input a positive integer")
else if(n%%2==0)
n<-n/2
else
n<-3*n+1
it is ok ,my question is that can we only write one line under each judgement? if I want to do something more after each judge, what should I do ,just like this case, I want to change the value of n,but also want to display it, what should I do? thank you very much
To be precise, this is not about lines but about statements. You can have the whole if else statement in one line:
> if (TRUE) 1 else 3
[1] 1
A statement will end at the end of the line (if complete), you can see that nicely in interactive mode if you enter the code line by line:
> if (TRUE)
+ 1
[1] 1
> else
Fehler: Unerwartete(s) 'else' in "else" # error: unexpected 'else' in "else"
> 3
[1] 3
if can come in form if (condition) statement or if (condition) statement else other.statement, the interpreter assumes the first version is meant if the statement is complete after line 2 - in interactive mode it cannot sensibly wait whether an else appears next. This is different in sourced code - there it is clear with the next line which form it is.
Semicolons end statements as well:
> if (TRUE) 1; else 3
[1] 1
Fehler: Unerwartete(s) 'else' in " else" # error: unexpected 'else' in "else"
But you can only have one statement in each branch of the condition.
> if (TRUE) 1; 2 else 3
[1] 1
Fehler: Unerwartete(s) 'else' in " 2 else" # error: unexpected 'else' in "2 else"
Curly braces group statements so they appear as one statement.
> if (TRUE) {1; 2} else 3
[1] 2
You have to use {} for allows the if statement to have more than one line. Try this:
n<-857
while(n!=1){
if(n<=0){
print("please input a positive integer")
}
else if(n%%2==0){
n<-n/2
print(n)
}
else {
n<-3*n+1
print(n)
}
}
To group statements, surround them with curly braces as you've done with the while loop:
if(n<=0) {
print("please input a positive integer")
} else if(n%%2==0) {
n<-n/2
print(n)
} else {
n<-3*n+1
print(n)
}
This will allow you to place multiple statements inside the if, the else if and the final else.
while the direct answer is, as has been noted, to use curly braces;
it is worth adding that you can integrate the <- assignment operator into many functions.
In your specific case:
print(n <- 3*n+1)
## instead of
# n <- 3*n+1
# print(n)
note that using = here will NOT work. It must be <-
Yes, you can use curly braces to contain more than statements for each conditional statement:
if (condition){
statement 1
print()
}
else{
statement 2
print()
}
Addition: if you want to use only if and else statement in one line you can use this:
ifelse(condition, statement1, statement2)
Ever heard of curly barces?
n<-857
while(n!=1){
if(n<=0) {
print("please input a positive integer")
} else if(n%%2==0) {
n<-n/2
print(n)
} else {
n<-3*n+1
print(n)
}
}

Resources