R中的嵌套for循环 - 最终结果的问题

时间:2012-06-12 04:15:11

标签: r loops for-loop nested

当只知道分布的时刻时,我正在解决重建(或恢复)概率分布函数的问题。我已经用R编写了代码,虽然逻辑对我来说似乎是对的,但我没有得到我想要的输出。

我试图用作近似(或重建或恢复)的CDF的等式是您在下图中看到的。我正在编写等式右边的代码,并将其等同于我在代码中称为F的向量。

可以在此处找到包含原始等式的纸张链接。

在论文中标记为等式(2)。

这是我写的代码:

#R Codes:  
alpha <- 50
T <- 1
x <- seq(0, T, by = 0.1)

# Original CDF equation
Ft <- (1-log(x^3))*(x^3)  
plot(x, Ft, type = "l", ylab = "", xlab = "")

# Approximated CDF equation using Moment type reconstruction
k<- floor(alpha*y/T)  
for(i in 1:length(k))  
{
for(j in k[i]:alpha)  
{  
F[x+1] <- (factorial(alpha)/(factorial(alpha-j)*factorial(j-k)*factorial(k)))*(((-1)^(j-k))/(T^j))*((9/(j+3))^2)
}
}
plot(x[1:7], F, type = "l", ylab = "", xlab = "")

这里有任何帮助,因为使用我的代码获得的近似值和图表与原始曲线有很大不同。

2 个答案:

答案 0 :(得分:1)

很明显你的问题就在这里。

F[x+1] <- (factorial(alpha)/(factorial(alpha-j)*factorial(j-k)*factorial(k)))*(((-1)^(j-k))/(T^j))*((9/(j+3))^2)

你试图在x中获得不同的东西,是吗?那么你怎么能得到这个,如果这个等式的右边没有x的变化,而左边有一个使用非整数指数的赋值?

答案 1 :(得分:0)

    alpha <- 30  #In the exemple you try to reproduce, they use an alpha of 30 if i understood correctly (i'm a paleontologist not a mathematician so this paper's way beyond my area of expertise :) )

    tau <- 1  #tau is your T (i changed it to avoid confusion with TRUE)
    x <- seq(0, tau, by = 0.001)
    f<-rep(0,length(x))  #This is your F (same reason as above for the change). 
    #It has to be created as a vector of 0 before your loop since the whole idea of the loop is that you want to proceed by incrementation.

    #You want a value of f for each of your element of x so here is your first loop:
    for(i in 1:length(x)){

    #Then you want the sum for all k going from 1 to alpha*x[i]/tau:
        for(k in 1:floor(alpha*x[i]/tau)){

    #And inside that sum, the sum for all j going from k to alpha:
            for(j in k:alpha){

    #This sum needs to be incremented (hence f[i] on both side)
                f[i]<-f[i]+(factorial(alpha)/(factorial(alpha-j)*factorial(j-k)*factorial(k)))*(((-1)^(j-k))/(tau^j))*(9/(j+3)^2)
                }
            }
        }

    plot(x, f, type = "l", ylab = "", xlab = "")