[英]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. “ $ a”和“ $ b”标签正在丢失。
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
. 这是另一个版本,可以提供您想要的结果,但不需要功能
f
和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.