0

This is probably a silly question but here goes: I want to fit parameter "a" from x^a using mle in R. When x>=0, I want the function to read:

x^a

When x<0, I want however the function to change into

-(-x)^a

. A simple "if-else" specification in the code does not work. For example:

Q<-function(r){
    if(r>=0){r^a}
    else{-(-r)^a}
  }

The program returns the following warning:

the condition has length > 1 and only the first element will be used

Has anyone else encountered a similar challenge? At face value this seems like a problem similar to a piecewise regression...But how would one implement this in a mle function? Thanks!

  • 1
    Did you use `ifelse()` or `if() {} else {}`? Please show the code that actually produced the error. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 28 '18 at 18:31
  • As a first step I was looking for a simple tip to a possibly quite straight-forward topic. Ultimately, I want to use the mle function in R to fit a parameter of a function whose functional form changes according to the value of its argument. – Orestis Kopsacheilis Nov 28 '18 at 19:11
  • Use `Q<-function(r) ifelse(r>=0, r^a, -(-r)^a)`. Your function should be properly vectorized. – MrFlick Nov 28 '18 at 19:49
  • Thanks @MrFlick, this syntax seems to have done the trick! – Orestis Kopsacheilis Nov 29 '18 at 00:34

0 Answers0