Problem with R function

Hi,
I've a problem with this function:
k <- function(x){
if(x > 0) {2exp(-2x)}
if(x < 0) {0*x}
}

I can't integrate it like I want:

integrate(k, -Inf, +Inf)

It gives this error:
Error in integrate(k, -Inf, +Inf) :
evaluation of function gave a result of wrong length
In addition: Warning messages:
1: In if (x > 0) { :
the condition has length > 1 and only the first element will be used
2: In if (x < 0) { :
the condition has length > 1 and only the first element will be used

Can somebody help me to write it right?

You've done a couple of things that are impermissible in R coding.

First, 2x is not a valid way to express multiplication. You must use 2 * x.

Second, if requires a single logical value. To do a conditional over a vector you must use either ifelse or indexing.

You may want to redefine k as

k <- function(x){
  ifelse(x > 0, 2 * exp(-2 * x), 0)
}

Or, slightly more efficient, using indexing

k <- function(x){
  positive <- x > 0
  x[positive] <- 2 * exp(-2 * x[positive])
  x[!positive] <- 0
  x
}
1 Like

When I cut pasted it hadn't taken *.

You've resolved my problem. Thanks!!!

:grin: