具有多个输出的R分段函数

时间:2016-02-03 01:09:45

标签: r

我有两个函数,每个函数返回两个值(作为列表),并在一个有限的域上运行:

# 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) { return(ifelse(x < 0, g(x), f(x))) }

我想得到这个:

> 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

相反,我得到了这个:

> 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

&#34; $ a&#34;和&#34; $ b&#34;标签迷路了。

只需一次输入,情况就更糟了:

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

我做错了什么?

我如何实现目标?

1 个答案:

答案 0 :(得分:1)

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