Unexpected 'else' in "else" error - r

I get this error:
Error: unexpected 'else' in " else"
From this if, else statement:
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) }
else {
if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) }
else {
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) } }
What is wrong with this?

You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
}
To put it more simply, if you have:
if(condition == TRUE) x <- TRUE
else x <- FALSE
Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:
if(condition == TRUE) {x <- TRUE
} else {x <- FALSE}

I would suggest to read up a bit on the syntax. See here.
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)

I dislike braces (too much python programming I guess). My solution for simple if else like
if(condition == TRUE) {x <- TRUE
} else {x <- FALSE}
is
if(condition == TRUE)
x <- TRUE
else
x <- FALSE
is clear enough.

Related

If-else statement inside apply function R

I am writing an apply function in R to search a table and return all the instances that TRUE occurs, and I have written the following code but it keeps giving me errors, and I am not sure why. Any help is appreciated.
xsum = apply(genomeTable, 1, function(i) {
if (i) < q.start | if (i) > q.end{
return FALSE
} else{
return TRUE
}
})
sum(xsum)
Your if statement is duplicated. You only need one if for the condition. Parenthesis need to wrap the whole condition. Try this:
xsum = apply(genomeTable, 1, function(i) {
if (i < q.start | i > q.end) {
return(FALSE)
} else {
return(TRUE)
}
})
Try this:
xsum = apply(genomeTable, 1, function(i) ifelse ((i < q.sta | i > q.end), FALSE, TRUE))
It does not work, please provide some data.

R, problems using a for cycle inside if else

I am trying to check if all the elements inside a vector are the same. I am using this code:
if( isTRUE(for(i in 1:length(x)){x[1]==x[i]})){print(x[1])} else{print("several")
Now suppose
x <- c(0,0,0,0,0,0,0,0,0,0,0)
Here, the code should return "0" and if
x <- c(0,0,0,0,0,1,0,0,0,0,0)
it should return "several". In both cases I get "several", any idea why is not working as desired?
Thank u in advance.
there is a simpler way:
if (length(unique(x)) == 1) {
print(x[1])
} else {
print("several")
}
If you want to compare all components of x with the first component you should use all instead of a for loop:
if (all(x == x[1])) {
print(x[1])
} else {
print("several")
}
The result of both approaches is the same.

Non-execution of statement in function calling

While working on some problem i came across a situation in which i wanted to know if a function was executed when called upon. To do so i put a print statement in the function.
abc = function(x)
if(x > 0) {
return(x)
print("Go")
} else {
return(0)
print("Run")
}
y = abc(3)
y
# [1] 3
Why print statement is not executed while calling abc()?
That is because you are returning before printing. Change the sequence of those two statements and it should print
abc = function(x) {
if(x > 0) {
print("Go")
return(x)
} else {
print("Run")
return(0)
}
}
abc(3)
#[1] "Go"
#[1] 3
abc(-3)
#[1] "Run"
#[1] 0

Three function in R

IS <- function(N,K,sigma,t,r,S_0,a,b,tol){
funct_1 <- function(x){
return((S_0*(exp(-0.5*(sigma^2)*t+sigma*sqrt(t)*x))*(sigma*sqrt(t)-x))+
(exp(-r*t))*K*x)
}
bisection_method <- function(a, b, tol, f = funct_1){
if (f(a)*f(b) > 0){
print("No root found.")
} else
while ((b - a)/2.0 > tol){
midpt= (a + b)/2.0
if (f(midpt) == 0){
return(midpt)
} else if (f(a)*f(midpt) < 0){
b = midpt
} else
a = midpt
}
return(midpt)
}
}
The above function will produce nothing for you. My goal that to input the values of "N,K,sigma,t,r,S_0, a,b" and somehow return "midpt" for me. I have searched a lot but could not come up with anything that makes sense. I have many problems, assume that I input everything things, then how the function "funct_1" will output expression, this expression needs to be recalled to the next function "bisection_method} along with the value of a and b then finally obtain the "midpt" value. Any suggestions are really appreciated. Please let me know if there is anything not clear to you at all.
Your main function doesn't return anything. It just creates the auxiliary functions and then do nothing. That's why you're getting no output.
Try returning the bisection method with appropriate parameters in your main function instead. I also edited so you get NULL output when no root is found.
IS <- function(N,K,sigma,t,r,S_0,a,b,tol){
funct_1 <- function(x){
return((S_0*(exp(-0.5*(sigma^2)*t+sigma*sqrt(t)*x))*(sigma*sqrt(t)-x))+
(exp(-r*t))*K*x)
}
bisection_method <- function(a, b, tol, f = funct_1){
if (f(a)*f(b) > 0){
print("No root found."); return(NULL)
} else
while ((b - a)/2.0 > tol){
midpt= (a + b)/2.0
if (f(midpt) == 0){
return(midpt)
} else if (f(a)*f(midpt) < 0){
b = midpt
} else
a = midpt
}
return(midpt)
}
return(bisection_method(a,b,tol,funct_1))
}
Figured out some parameter combination that makes sense:
IS(1,1,1,4,5,1,.1,9,10^-4)
[1] 2.000023

Error in R-function when input is string

I have made a function that tests which numbers in a range that are multiple of 6 and/or 3, or none of them.
Multi <- function(x,y) {
z = x:y
for (i in z) {
if (i%%1!=0 | i<0) {
print("Error!")
break
} else if (i%%3==0 & i%%6==0) {
print(paste(i, "is multiple of both 3 and 6"))
} else if (i%%3==0) {
print(paste(i, "is multiple of 3"))
} else {
print(paste(i, "is not multiple"))
}
}
}
The loop works as I want it to, but within the first if-statement, I would also like it to print "Error!" if a character/string is provided. The message I get when trying Multi("Hello",10) is:
Error in x:y : NA/NaN argument
In addition: Warning message:
In Multi("Hello", 10) : NAs introduced by coercion
I have tried the suppressWarnings() function, but I couldn't make it work.
Any suggestions?
Try this:
Multi <- function(x,y) {
if (!is.numeric(x) | !is.numeric(y)) {
print("Error!")
} else {
z = x:y
for (i in z) {
if (i%%1!=0 | i<0) {
print("Error!")
break
} else if (i%%3==0 & i%%6==0) {
print(paste(i, "is multiple of both 3 and 6"))
} else if (i%%3==0) {
print(paste(i, "is multiple of 3"))
} else {
print(paste(i, "is not multiple"))
}
}
}
}
Multi(1,10)
Multi('Hello', 10) # now it will print Error without a NaN: 'Hello':10 was causing this NaN
You can reduce the code a little bit also
sapply(1:10, function(i) ifelse(i%%3==0,
ifelse(i%%6==0,
paste(i, "is multiple of both 3 and 6"),
paste(i, "is multiple of 3")),
paste(i, "is not multiple")))

Resources