[英]How to define a piecewise function in R
I want to define a piecewise function using R, however, my R code goes wrong. 我想用R定义一个分段函数,但是,我的R代码出错了。 Any suggestion is welcome.
任何建议都是受欢迎的。
x<-seq(-5, 5, by=0.01)
for (x in -5:5){
if (-0.326 < x < 0.652) fx<- 0.632
else if (-1.793<x<-1.304) fx<- 0.454
else if (1.630<x<2.119) fx<-0.227
else fx<- 0 }
Try this: 试试这个:
x <- seq(-5, 5, 0.01)
fx <- (x > -0.326 & x <0.625) * 0.632 +
(x > -1.793 & x < -1.304) * 0.454 +
(x > 1.630 & x < 2.119) * 0.227
plot(x, fx)
I'm a little late to the party, but I couldn't resist posting a couple more ways to do this. 我参加派对有点晚了,但我无法抗拒发布更多方法。 Both take advantage of R capabilities for working with intervals on the real line.
两者都利用R功能来处理实线上的间隔。
If you define your cut points and function values in the vectors cuts
and vals
like so: 如果在向量
cuts
和vals
定义切割点和函数值,如下所示:
cuts <- c( -Inf, -1.793, -1.304, -0.326, 0.625, 1.630, 2.119 )
vals <- c( 0, 0.454, 0, 0.632, 0, 0.227, 0 )
Then you can use findInterval
to efficiently look up the values of x
in your cutpoints: 然后,您可以使用
findInterval
在findInterval
中有效地查找x
的值:
fx <- vals[findInterval(x, c(-Inf, cuts))]
If this function needed to do fancier stuff than just look up a constant value, you can put expressions or functions or whatever you want in vals
, possibly using a list
if you want. 如果这个函数需要做更高级的东西,而不仅仅是查找一个常量值,你可以在
vals
放置表达式或函数或任何你想要的东西,如果你想要的话可能使用一个list
。
Alternatively, since this function is a step function, you can use stepfun
: 或者,由于此功能是步进功能,您可以使用
stepfun
:
f <- stepfun(cuts[-1], vals)
fx <- f(x)
Then you also get to use the nice plotting methods of stepfun
too. 然后你也可以使用
stepfun
的漂亮的绘图方法。
Or you could use ifelse
. 或者你可以使用
ifelse
。
fx <- ifelse(x > -0.326 & x <0.625, 0.632,
ifelse(x > -1.793 & x < -1.304, 0.454,
ifelse(x > 1.630 & x < 2.119, 0.227, 0)))
Maybe if you split the conditions 也许你分开条件
if((-1.793<x) & (x < 0.652)) ...
EDIT: This seems not to be all, here is a different approach: 编辑:这似乎不是全部,这是一个不同的方法:
x<-seq(-5, 5, by=0.01)
fx <- function(x) {
res <- rep(0, length(x))
res[(-0.326 < x) & (x < 0.652)] <- 0.632
res[(-1.793<x) & (x < (-1.304))] <- 0.454
res[(1.630<x) & (x <2.119)] <- 0.227
return(res)
}
fx(x)
Yet another option, this time using cut
. 还有另一种选择,这次使用
cut
。
regions <- c(-Inf, -1.793, -1.304, -0.326, 0.652, 1.63, 2.119, Inf)
group <- cut(x, regions)
f_values <- c(0, 0.454, 0, 0.632, 0, 0.227, 0)
(fx <- f_values[group])
Unless you have varying cutoff points, I'd use switch
. 除非你有不同的截止点,否则我会使用
switch
。 Here is an example w/ simplified cut values. 这是一个简化切割值的示例。
xcuts<-1:10 #the values at which you change fx assignment
xx<- seq(1.5,10,5, by =10) #vector of fx values to be selected
switch(max(which(x>xcuts)),
1= fx<-xx[1],
2= fx<-xx[2],
..."et cetera"...
)
Loop over x. 循环遍历x。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.