R Piecewise Function with Multiple Outputs -
i have 2 functions, each of return 2 values (as list) , operate on limited domain:
# x >= 0 f <- function(x) { return(list(a=x,b=2*x)) } # x < 0 g <- function(x) { return(list(a=x/2,b=x/4)) }
i want this:
fg <- function(x) { return(ifelse(x < 0, g(x), f(x))) }
and i'd this:
> fg(c(1,2)) a$ [1] 1 2 b$ [2] 2 4 > fg(c(-1,-2) a$ [1] -0.5 -1.0 b$ [2] -0.25 -0.50
instead, getting this:
> fg(c(1,2)) [[1]] [1] 1 2 [[2]] [1] 2 4 > fg(c(-1,-2)) [[1]] [1] -0.5 -1.0 [[2]] [1] -0.25 -0.50
the "$a" , "$b" labels getting lost.
with single input, it's worse:
> fg(1) [[1]] [1] 1
what doing wrong?
how can achieve objective?
i have modified code,
# x >= 0 f <- function(x) { return(list(a=x,b=2*x)) } # x < 0 g <- function(x) { return(list(a=x/2,b=x/4)) } fg <- function(x) { tmp <- lapply(x, function(y) switch(as.character(y > 0), 'true' = f(y), 'false' = g(y))) <- sapply(tmp, function(y) y$a) b <- sapply(tmp, function(y) y$b) out <- list(a = a, b = b) return(out) }
this version, gives results desire not need functions f
, g
. also, computation vectorised:
fg2 <- function(x) { list( = x * (1/2)^(x < 0), b = x * 2 * (1/8)^(x < 0) ) }
below examples,
> fg2(1) $a [1] 1 $b [1] 2 > fg2(1:2) $a [1] 1 2 $b [1] 2 4 > fg2(-2:2) $a [1] -1.0 -0.5 0.0 1.0 2.0 $b [1] -0.50 -0.25 0.00 2.00 4.00
Comments
Post a Comment