簡體   English   中英

在R中實施ECDF

[英]Implementing ECDF in R

我正在嘗試實現R函數ecdf()

我正在考慮兩種情況:一種是t一維的,另一種是以t為向量的。

#First case
my.ecdf<-function(x,t) {
            indicator<-ifelse(x<=t,1,0)
            out<-sum(indicator)/length(x)
            out
    }


#Second case
my.ecdf<-function(x,t) {
    out<-length(t)
    for(i in 1:length(t)) {
            indicator<-ifelse(x<=t[i],1,0)
            out[i]<-sum(indicator)/length(t)
    }
    out
}

如何檢查R函數ecdf()是否在做正確的事情? 該函數僅將x作為參數,因此我無法指定t的值。

一般提示-您可以通過在控制台中鍵入其名稱而無需括號或參數來查看任何函數的源代碼:

edcf
function (x) 
{
    x <- sort(x)
    n <- length(x)
    if (n < 1) 
        stop("'x' must have 1 or more non-missing values")
    vals <- unique(x)
    rval <- approxfun(vals, cumsum(tabulate(match(x, vals)))/n, 
        method = "constant", yleft = 0, yright = 1, f = 0, ties = "ordered")
    class(rval) <- c("ecdf", "stepfun", class(rval))
    assign("nobs", n, envir = environment(rval))
    attr(rval, "call") <- sys.call()
    rval
}

您可以對結果進行繪圖,然后看到結果非常相似:

# slightly improved version of my.ecdf
my.ecdf<-function(x,t) {
  out<-numeric(length(t))
  for(i in 1:length(t)) {
    indicator <- as.numeric(x<=t[i])
    out[i] <- sum(indicator)/length(t)
  }
  out
}
# test 1
x <- rnorm(1000)
plot(ecdf(x))
lines(seq(-4, 4, length=1000), 
     my.ecdf(x, seq(-4, 4, length=1000)), 
     col='red')
# test 2
x <- rexp(1000)
plot(ecdf(x))
lines(seq(0, 8, length=1000), 
     my.ecdf(x, seq(0, 8, length=1000)), 
     col='red')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM