Reputation: 1
I have stumbled upon a question I am struggling to tackle.
"Write a function that accepts a vector of integers and returns a logical vector that is TRUE whenever the input is even, FALSE whenever the input is odd and NA whenever the input is nonfinite (that is if it is Inf, -Inf, NA, NaN). Check that it works with positive, negative, zero and nonfinite inputs."
f <- function(x,y)
{
if (x==Inf)
{
print ("NA")
}else
if(x%%2=0)
{print ("TRUE")
}else
{print("FALSE")}
if (y==Inf)
{print("NA")
}
else
if (y%%2==0)
{print ("TRUE")
} else
{print ("FALSE")
}
print(c(x+y, x-y, x^4-y^3, x^2+y^2, y*x))
}
Through my eyes I cannot see where I have gone wrong. I receive an error code saying "Error: unexpected '}' in "}""
Any guidance would be greatly appreciated.
Upvotes: 0
Views: 994
Reputation: 522471
The problem with your current approach is that you are trying to operate on a vector, but your if
- else
logic is really meant to operate on scalars (i.e. single values). I recommend using a vectorized solution, such as the ifelse()
function. We could chain together a bunch of calls to ifelse
, but it might be easier here to use case_when
from the dplyr
package:
library(dplyr)
f <- function(x) {
result <- case_when(
x %% 2 == 0 ~ TRUE,
x %% 2 == 1 ~ FALSE,
is.infinite(x) ~ NA,
is.nan(x) ~ NA,
TRUE ~ NA
)
return(result)
}
Edit:
I rather like the answer by @markus, which may be exactly what your teacher is expecting. But using case_when
as I have above makes the mapping you are expecting explicit. So, from a code clarity point of view, it is completely clear what is going on.
Upvotes: 1
Reputation: 26363
You could shorten your function a bit and write
f <- function(x) { x %% 2 == 0 }
Test
f(c(1:6, Inf, -Inf, NA, NaN))
# [1] FALSE TRUE FALSE TRUE FALSE TRUE NA NA NA NA
Upvotes: 2