Petas Zwegas
Petas Zwegas

Reputation: 85

Ifelse in function returning NaN for negative numbers

I dont understand why this function returns NaN for negative values of x.

lambda <- 2.77 
alpha <- 0.88 

# function 

util <- function( x, a, l){
  
  ifelse(x >=0, x^a, l * (x^a) )
  
}

for x I insert a number from a data frame. If the number is positive, I get the correct result. If it is negative though, it returns NaN


> util(-0.5,alpha,lambda)
[1] NaN

Can someone explain why or suggest a solution?

Upvotes: 2

Views: 193

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 102890

You can try this

util <- function(x, a, l) {
  ifelse(x >= 0, x^a, l * (as.complex(x)^a))
}

and you will see

> util(-0.5, alpha, lambda)
[1] -1.399432+0.554074i

Upvotes: 1

Related Questions