Why can't my function find arguments? - r

I'm trying to do a function that performs the bisection method. But I get a lot of errors that I don't understand. The code is:
bisection<-function(f,a,b,n=1000,tol=1e-9)
{
if(!(f(a)<0) && (f(b)>0)){stop};
elseif((f(a)>0) && (f(b)<0)){stop};
for (i in 1:n){
c=(a+b)/2;
if((f(c)==0)||((b-a)/2)<tol){return(c)};
elseif(sign(f(c))==sign(f(a)),a<-c,b<-c);
}
}
and I get the following from R:
> bisection<-function(f,a,b,n=1000,tol=1e-9)
+ {
+ if(!(f(a)<0) && (f(b)>0)){stop};
+ elseif((f(a)>0) && (f(b)<0)){stop};
Error: unexpected '{' in:
" if(!(f(a)<0) && (f(b)>0)){stop}
elseif((f(a)>0) && (f(b)<0)){"
> for (i in 1:n){
+ c=(a+b)/2;
+ if((f(c)==0)||((b-a)/2)<tol){return(c)};
+ #elseif(sign(f(c))==sign(f(a)),a<-c,b<-c);
+ }
Error: object 'n' not found
> }
Error: unexpected '}' in "}"
I would be most grateful if someone could point out what I've done wrong.
Thank you in advance!

I tried to correct your function. So it does not result in errors:
bisection<-function(f,a,b,n=1000,tol=1e-9)
{
if(!(f(a)<0) && (f(b)>0)){stop}
else if((f(a)>0) && (f(b)<0)){stop}
for (i in 1:n){
c=(a+b)/2
if((f(c)==0)||((b-a)/2)<tol){
return(c)
}
else if(sign(f(c))==sign(f(a))){
a<-c
b<-c
}
}
}
but I guess you want another else case in the last else if:
bisection<-function(f,a,b,n=1000,tol=1e-9)
{
if(!(f(a)<0) && (f(b)>0)){stop}
else if((f(a)>0) && (f(b)<0)){stop}
for (i in 1:n){
c=(a+b)/2
if((f(c)==0)||((b-a)/2)<tol){
return(c)
}
else if(sign(f(c))==sign(f(a))){
a<-c
}else{
b<-c
}
}
}
Furthermore, it looks like you confused the concept of ifelse with else if.
See for ifelse: https://www.datamentor.io/r-programming/ifelse-function
and else if: https://www.datamentor.io/r-programming/if-else-statement

Related

R guessing game syntax

I'm having trouble with proper bracket syntax when making a guessing game. Here is a brief example of my code
number_result <- readline(prompt = "Choose a number btwn 1 & 100: ")
input <- 0
rand <- sample(seq(1,100), size = 1)
input = number_result
while(input != rand){
if(input < rand){
print("Higher!")
}
else if(input > rand){
print("Lower!")
}
else(input = rand){
return(print("You got it!"))
}
}
My error is:
Error: unexpected '{' in:
" }
else(input = rand){"
> return(print("You got it!"))
[1] "You got it!"
Error: no function to return from, jumping to top level
> }
Error: unexpected '}' in "}"
> }
Error: unexpected '}' in " }"
>
No return needed because you didn't define a function. You must also specify a stopping condition! Otherwise your while will run forever.
try this
number_result <- readline(prompt = "Choose a number btwn 1 & 100: ")
input <- 0
rand <- sample(seq(1,100), size = 1)
input = number_result
while(input != rand){
if(input < rand){
print("Higher!")
} else if(input > rand){
print("Lower!")
} else {
print("You got it!")
}
input <- input + 1
}

Why can't I use in with an if condition

I have the following code:
x=rnorm(100,0,1)
x
a=0
for(i in x){
if(i in -1:1){
a<-a+1
}
}
I'm getting the following error:
Geeting error unexpected '}' in " }"
What am I doing wrong?
I changed the condition in the if statement. Is this what you want?
x=rnorm(100,0,1)
x
a = 0
for(i in x){
if(i > -1 & i < 1){
a <- a + 1
}
}

unexpected numeric constant graph

The requirement is using R base function to build up a function like this:
Function - is_isomorphic
Input - g1, a graph object; g2, a graph object.
Output - true if g1 and g2 are isomorphic, false if not.
Description - Check if the graph objects are isomorphic, meaning all vertices, edges, and weights are identical. Comparison of vertices should be based on names not indexes, indexes should only be used if vertex labels are not defined.
My code is as follows:
isomorphic <- function(g1,g2){
##first calculate number of vertices, if not equal, return false
if(length(g1) != length(g2)){
return FALSE
##then compare each vertix and its related edges and weights
} else {
for(i in 1:length(g1)){
for(j in 1:length(g2)){
if(names(g1[i]) == names(g2[j]){
flag = 1
if(g1[[i]]$edges != g2[[j]]$edges){
return FALSE
} else {
if(g1[[i]]$weights != g2[[j]]$weights){
return FALSE
} else {
return TRUE
}
}
}
}
if(flag != 1){
return FALSE
}
}
}
}
wrong message:
isomorphic <- function(g1,g2){
+ ##first calculate number of vertices, if not equal, return false
+ if(length(g1) != length(g2)){
+ return FALSE
Error: unexpected numeric constant in:
" if(length(g1) != length(g2)){
return FALSE"
> ##then compare each vertix and its related edges and weights
> } else {
Error: unexpected '}' in " }"
> for(i in 1:length(g1)){
+ for(j in 1:length(g2)){
+ if(names(g1[i]) == names(g2[j]){
Error: unexpected '{' in:
" for(j in 1:length(g2)){
if(names(g1[i]) == names(g2[j]){"
> flag = 1
> if(g1[[i]]$edges != g2[[j]]$edges){
+ return FALSE
Error: unexpected numeric constant in:
" if(g1[[i]]$edges != g2[[j]]$edges){
return FALSE"
> } else {
Error: unexpected '}' in " }"
> if(g1[[i]]$weights != g2[[j]]$weights){
+ return FALSE
Error: unexpected numeric constant in:
" if(g1[[i]]$weights != g2[[j]]$weights){
return FALSE"
> } else {
Error: unexpected '}' in " }"
> return TRUE
Error: unexpected numeric constant in " return TRUE"
> }
Error: unexpected '}' in " }"
> }
Error: unexpected '}' in " }"
> }
Error: unexpected '}' in " }"
> }
Error: unexpected '}' in " }"
>
> if(flag != 1){
+ return FALSE
Error: unexpected numeric constant in:
" if(flag != 1){
return FALSE"
> }
Error: unexpected '}' in " }"
> }
Error: unexpected '}' in " }"
> }
Error: unexpected '}' in " }"
> }
Error: unexpected '}' in "}"
Go aback and read the Intro to R to understand the syntax. Part of the problem is that 'return' is a function call and you have to have the value in parends.
Also get a text editor that highlights parends and bracket since you were missing some. Here is a function that is valid:
> isomorphic <- function(g1,g2){
+ ##first calculate number of vertices, if not equal, return false
+ if(length(g1) != length(g2)){
+ return( FALSE)
+ ##then compare each vertix and its related edges and weights
+ } else {
+ for(i in 1:length(g1)){
+ for(j in 1:length(g2)){
+ if(names(g1[i]) == names(g2[j])){
+ flag = 1
+ if(g1[[i]]$edges != g2[[j]]$edges){
+ return( FALSE )
+ } else {
+ if(g1[[i]]$weights != g2[[j]]$weights){
+ return (FALSE)
+ } else {
+ return( TRUE)
+ }
+ }
+ }
+ }
+
+ if(flag != 1){
+ return( FALSE)
+ }
+ }
+ }
+ }
>

for loop with if else statement in R

I know lots of people have posted about this, and I did look through the answers to write my code, but it's still not working... Can someone point out where i'm doing wrong please? many thanks in advance!
for(j in 1:1000){
for(i in 1:52){
if (i == 1){
r.sims[i,] <- r.sims[1]
}
else if (i == 2){
r.sims[i,] <- r.sims[2]
}
else (i > 2){
r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
}
}
}
i have the following errors
Error: unexpected '{' in:
" }
else (i > 2){"
> r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
Error in r.sims[i, ] <- r.sims[i - 1, ] * ar1 + r.sims[i - 2, ] * ar2 + :
replacement has length zero
> }
Error: unexpected '}' in " }"
>
> }
Error: unexpected '}' in " }"
>
> }
Error: unexpected '}' in " }"
>
Without understanding what your code is supposed to do, I have nevertheless made an example of how you might fix your script. I think the key is that you need to supply curly brackets {...} following your else statement in order for it to consider the following code.
Example:
r.sims <- matrix(runif(52)*100, nrow=52, ncol=100)
e.sims <- matrix(runif(52)*100, nrow=52, ncol=100)
ma1 <- 1
ar1 <- 2
ar2 <- 3
for(j in 1:1000) {
for(i in 1:52) {
if (i == 1) {
r.sims[i,] <- r.sims[1]
} else {
if(i == 2) {
r.sims[i,] <- r.sims[2]
} else {
if(i > 2) {
r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
}
}
}
}
}
You seem to misunderstand the concept of else.
else covers all cases that didn't match previous if or else if statements.
Therefore, you cannot specify any condition for else.
To cover all cases where i is not 1 or 2 simply use else, without any () brackets.
If you want to have a condition, use else if (condition).

Unexpected 'else' in "else" error

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.

Resources