08223003
08223003

Reputation: 5

Real and Natural numbers in R

I am trying to create a function which takes in an inputs and outputs the factorial of the number. If the input to the function is a real number, but not a natural number, round n to the nearest natural number and print a warning message alerting the user to this behavior.

My questions is: How do I check if the input is real or natural number?

Upvotes: 0

Views: 1889

Answers (3)

Maurits Evers
Maurits Evers

Reputation: 50718

"How do I check if the input is real or natural number?"

We can use as.integer

is.natural <- function(x) as.integer(x) == x & x > 0
is.natural(3)
[1] TRUE
is.natural(0)
[1] FALSE
is.natural(1.5)
[1] FALSE

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 102251

Here is a custom function

f <- function(x) {
  if (x<=0 | x%%1!=0) warning("Input is not natural number!")
  factorial(max(1,as.integer(x)))
}

Example

> f(3.5)
[1] 6
Warning message:
In f(3.5) : Input is not natural number!

> f(3)
[1] 6

> f(0.1)
[1] 1
Warning message:
In f(0.1) : Input is not natural number!

> f(-0.1)
[1] 1
Warning message:
In f(-0.1) : Input is not natural number!

Upvotes: 0

Georgery
Georgery

Reputation: 8117

This might help:

myFactorial <- function(x){
    if (any(x %% 1 != 0 | is.na(x))) message("Not all elements of the vector are natural numbers.")
    factorial(floor(x))
}

Upvotes: 1

Related Questions