[英]Trouble with the ifelse() statement in R
我有一个家庭作业,必须编写一个Bessel函数并将其与r中的内置Bessel函数进行比较。 我必须在区间(0.01:10)上绘制曲线。 该函数具有多个部分,对于区间0 <= x <= 3,我必须使用公式1找到x。在区间3 <x <=无穷大时,我必须使用公式2。我尝试了if和else,但是我一直收到“长度> 1,所以使用第一个元素”的消息。 我发现对于向量,我需要ifelse语句,但实际上该如何使用它呢? 我玩过它,发现它只做true / false类型的东西。 即ifelse(x <= 3,y,z),其中所有小于x且等于x的数字均为y,所有大于x的数字均为z。 如果x <= 3且所有其他数字的方程式2如何在方程式1处编写函数?
我提供的代码是错误的,可能是草率的,但是我已经在r上玩了一个星期了,这已经可以进行了
x <- seq(.01,10, .01) #sequence of numbers 0.01 - 10 in 0.01 intervals.
#Bessel function for a set of numbers
bess.J = function(x){
if(x<=3){
#
less3 = 1-2.249997*(x/3)^2+1.2656208*(x/3)^4-0.31638*(x/3)^6+0.044479* (x/3)^8-0.0039444*(x/3)^10+0.00021*(x/3)^12
return(less3)
}
#
else{
Tgreater3 = x - 0.78539816 - 0.04166397*(3/x) - (0.00003954*(3/x)^2) + (0.00262573*(3/x)^3) - (0.00054125*(x/3)^4) - (0.00029333*(3/x)^5) + (0.00013558*(3/x)^6)
Fgreater3 = 0.79788456 - 0.0000077*(3/x) - (0.00552740*(3/x)^2) - (0.00009512*(3/x)^3) + (0.00137237*(3/x)^4) - (0.00072805*(3/x)^5) + (0.00014476*(3/x)^6)
Jgreater3 = x^(-1/2)*Fgreater3*cos(Tgreater3)
return(Jgreater3)
}
}
plot(x,bess.J(x))
如您所说,可以使用ifelse()
代替if和else。 我创建了2个函数(equation1和equation2),以使代码更具可读性。
equation1 <- function(x){
1-2.249997*(x/3)^2+1.2656208*(x/3)^4-0.31638*(x/3)^6+0.044479* (x/3)^8-0.0039444*(x/3)^10+0.00021*(x/3)^12
}
equation2 <- function(x){
Tgreater3 = x - 0.78539816 - 0.04166397*(3/x) - (0.00003954*(3/x)^2) + (0.00262573*(3/x)^3) - (0.00054125*(x/3)^4) - (0.00029333*(3/x)^5) + (0.00013558*(3/x)^6)
Fgreater3 = 0.79788456 - 0.0000077*(3/x) - (0.00552740*(3/x)^2) - (0.00009512*(3/x)^3) + (0.00137237*(3/x)^4) - (0.00072805*(3/x)^5) + (0.00014476*(3/x)^6)
Jgreater3 = x^(-1/2)*Fgreater3*cos(Tgreater3)
return(Jgreater3)
}
bess.J <- function(x){
ifelse(x <= 3, equation1(x), equation2(x))
}
plot(x, bess.J(x))
一种可能的解决方案是编写两个函数,每个方程式一个,然后使用ifelse
将x变量传递给适当的方程式。
下面我在x <= 3时定义函数“ eq1”,并在x> 3时定义“ eq2”。
x <- seq(.01,10, .01) #sequence of numbers 0.01 - 10 in 0.01 intervals.
#Bessel function for a set of number
eq1<- function(x) {
less3 = 1-2.249997*(x/3)^2+1.2656208*(x/3)^4-0.31638*(x/3)^6+0.044479* (x/3)^8-0.0039444*(x/3)^10+0.00021*(x/3)^12
return(less3)
}
eq2<- function(x){
Tgreater3 = x - 0.78539816 - 0.04166397*(3/x) - (0.00003954*(3/x)^2) + (0.00262573*(3/x)^3) - (0.00054125*(x/3)^4) - (0.00029333*(3/x)^5) + (0.00013558*(3/x)^6)
Fgreater3 = 0.79788456 - 0.0000077*(3/x) - (0.00552740*(3/x)^2) - (0.00009512*(3/x)^3) + (0.00137237*(3/x)^4) - (0.00072805*(3/x)^5) + (0.00014476*(3/x)^6)
Jgreater3 = x^(-1/2)*Fgreater3*cos(Tgreater3)
return(Jgreater3)
}
bess.jx<-ifelse(x<=3, eq1(x), eq2(x))
plot(x,bess.jx)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.