Error in R-function when input is string - r

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")))

Related

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

Unexpected bracket when using "if" inside function [duplicate]

This question already has answers here:
if/else constructs inside and outside functions
(2 answers)
Closed 5 years ago.
I constructed the function, but the R gives me the error. But I does not know what I did wrongly.
Error: unexpected '}' in "}"
Vect_fun=function(x,a) {
if(a=1)
{
y= mean(x,na.rm=TRUE)
}
else{
if(a=2)
{
y= na.aggregate(x)
}
else {
y=x[!is.na(x)]
}
}
y
}
Use double equal sign to comparing.
Vect_fun = function(x, a) {
if (a == 1) {
y = mean(x, na.rm = TRUE)
}
else {
if (a == 2) {
y = na.aggregate(x)
}
else {
y = x[!is.na(x)]
}
}
y
}
Your formatting is off in addition to needing to use the proper == operator, and else if
You should indent at each level so it's easier to read, and you need to use == for logical operators. Also, else{ if(){ }} is messy. Use else if{ }
Vect_fun <- function(x,a) {
if (a == 1) {
y = mean(x, na.rm = TRUE)
} else if (a == 2) {
y = na.aggregate(x)
return(y)
} else {
y = x[!is.na(x)]
}
return(y)
}

Use result of previous loop as input for next loop

I have the code below, which seems to accomplish what I'm trying to do but also throws the error output shown below the code. What I'm trying to do, is run through the loop the first time with x = 1, then for each time the loop runs after that I want x = y, the result of the previous loop. I always fumble with loops so any tips are greatly appreciated.
Code:
for(i in 1:5)
{
if(i=1)
{
x<-1
}
else
{
x<-y
}
y<-x*i
y
}
ERRORS:
for(i in 1:5)
+ {
+ if(i=1)
Error: unexpected '=' in:
"{
if(i="
> {
+ x<-1
+ }
> else
Error: unexpected 'else' in " else"
> {
+ x<-y
+ }
> y<-x*i
> y
[1] 25
> }
Error: unexpected '}' in "}"
Here is your code re-written with slightly clearer syntax
for (i in 1:5) {
if (i == 1) {
x <- 1
} else {
x <- y
}
y <- x * i
}
Or even better syntax.
for (i in 1:5) {
x <- ifelse(i == 1, 1, y)
y <- x * i
}

Nested IF function in R [duplicate]

This question already has an answer here:
R "Error: unexpected '}' in "}" [duplicate]
(1 answer)
Closed 5 years ago.
I am trying to build a function that takes 3 arguments, a vector, whether to display or not a graph, and if yes, the type of graph. Unfortunately, i get an error and don't understand why. (This is for a class but i already validated the points through reasoning, i just want to progress on my code...)
my_function <- function(x, display = FALSE, type) {
if (display = TRUE & type = "hist") {
hist(x)
} if (display = TRUE & type = "plot") {
plot(x)
} else {
summary(x)
}
}
I get multiples:
Error: unexpected '}' in " }"
You are using assignments in your if conditions instead of equality checks. In addition, you need to preface every if in a chain, other than the first one, with else. Try this code:
my_function <- function(x, display = FALSE, type) {
if (display == TRUE & type == "hist") {
hist(x)
} else if (display == TRUE & type == "plot") {
plot(x)
} else {
summary(x)
}
}

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