简体   繁体   中英

R Piecewise Function with Multiple Outputs

I have two functions, each of which return two values (as a list) and which operate over a limited domain:

# for x >= 0
f <- function(x) { return(list(a=x,b=2*x)) }
# for x < 0
g <- function(x) { return(list(a=x/2,b=x/4)) }

I want to do something like this:

fg <- function(x) { return(ifelse(x < 0, g(x), f(x))) }

And I'd like to get 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, I am 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" and "$b" labels are getting lost.

With a single input, it's even worse:

> fg(1)
[[1]]
[1] 1

What am I doing wrong?

How can I achieve my objective?

I have modified your code,

# for x >= 0
f <- function(x) { return(list(a=x,b=2*x)) }
# for 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)))
    a <- sapply(tmp, function(y) y$a)
    b <- sapply(tmp, function(y) y$b)
    out <- list(a = a, b = b)
    return(out)
}

This is another version, which gives the results you desire but does not need the functions f and g . Also, the computation is vectorised:

fg2 <- function(x) {
    list(
        a = x * (1/2)^(x < 0), 
        b = x * 2 * (1/8)^(x < 0)
    )
}

Below are some 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM