Conditional function problem with vector input

Hi, I tried to generate a conditional function in R for the following function
f(x)=\begin{cases} log(2-x)& 0<x<2\\ 0, &otherwise \end{cases}

f <- function(x){
  if(x>0 && x<2){log(2-x)} else{0}
  }

My function works when I separately input values but when I try to input a vector:

L = c(1,1.9,2,3)
f(L)
[1]  0.000000 -2.302585      -Inf       NaN

I found that all element in the vector was passed into the function log(2-x) but not following my if-else conditions, how should I solve this problem? Thanks.

1 Like

The ifelse function can be used for vectorized if tests. This works but still prints a warning because calculations are done and then filtered by the test condition.

f <- function(x){
+   ifelse(x>0 & x<2,log(2-x), 0)
+ }
L = c(1,1.9,2,3)
f(L)
[1]  0.000000 -2.302585  0.000000  0.000000
Warning message:
In log(2 - x) : NaNs produced
1 Like