R中的ifelse()语句出现问题

时间:2019-02-07 03:34:36

标签: r

我有一个家庭作业,必须编写一个Bessel函数并将其与r中的内置Bessel函数进行比较。我必须在区间(0.01:10)上​​绘制曲线。该函数具有多个部分,对于区间0 <= x <= 3,我必须使用公式1找到x。在区间3 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))

2 个答案:

答案 0 :(得分:1)

如您所说,您可以使用ifelse()代替if and else。我创建了2个函数(方程1和方程2),以使代码更具可读性。

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))

答案 1 :(得分:1)

可能的解决方案是编写两个函数,每个方程式一个,然后使用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)

enter image description here