plot画分段函数,R:绘制分段函数

博主在R中定义了一个分段函数g1,并遇到了在使用`curve()`绘制函数图时出现警告的问题。警告信息指出条件判断的长度大于1,仅使用了第一个元素。博主通过将`if-else`结构替换为`ifelse()`函数解决了绘图问题,但发现此问题还影响到其他命令,如尝试对g1进行积分时同样出现警告。解决方案是使用向量化操作的`ifelse()`函数来确保函数能够正确处理向量输入。
摘要由CSDN通过智能技术生成

I'm having some issues with the piecewise function I defined in R.

I've defined the function as:

g1

if (x <= 0.25) {

y

}

else if (x >= 0.75) {

y

}

else {y

y

}

where gs1,gs2,gs3 are functions I defined earlier.

In order to plot the function g1, I tried:

curve(g1)

but R displays the following:

Warning message:

In if (x <= 0.25) { :

the condition has length > 1 and only the first element will be used

I think the problem might be that R requires the argument of the function as a number instead of a vector? I'm not sure whether I'm right or not.

I figured out the plotting problem by using the following method:

xx

yy

plot(xx,yy,type='l')

But I still want to ask is there any way to deal with this kind of problem since I found that my piecewise function defined is not okay for many other commands either. For example, say I would like to integrate g1 over 0 to 1, if I just try "integrate" function in R, same warning message appears.

解决方案

your issue is that you are looking for vectorized if-else, give ifelse a try, or apply your function using result

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值