2017-09-02 52 views
0

我有一個問題,當我在循環中使用它時,會返回R中創建的函數的輸出。我正在嘗試將多個MCMC模型的輸出結合到一個R對象中。R問題返回函數使用循環的輸出

功能:

get_scrUN_output <- function(filename){ 
    out <- filename 
    nam<-c("sigma","lam0","psi", "N") 
    nam<-match(nam,dimnames(out[[1]]$sims)[[2]]) 

    out.lst<-mcmc.list(
     as.mcmc(out[[1]]$sims[200001:300000,nam]), 
     as.mcmc(out[[2]]$sims[200001:300000,nam]), 
     as.mcmc(out[[3]]$sims[200001:300000,nam])) 

    s <- summary(out.lst) 
    gd <- gelman.diag(out.lst,multivariate = FALSE) 

    output_table <- rbind(as.data.frame(t(s$statistics)), 
        as.data.frame(t(s$quantiles)), 
        as.data.frame(t(gd$psrf))) 
    return(output_table) } 

我用來創建RDATA MCMC輸出的列表通過函數來​​運行的代碼:當我使用功能上的單個輸出文件

scrUN.ET <- list.files(getwd(),"out.*ET.RData") 
    scrUN.lst <- as.vector(substring(scrUN.ET,1)) 
    scrUN.lst <- str_sub(scrUN.lst, 1, str_length(scrUN.lst)-3) 

    >scrUN.lst 
    [1] "BBout11FL" "BBout11TL" "BBout12TL" "BBout13FL" "BBout13TL" 

,它的工作原理:

get_scrUN_output(BBout11FL) 

    sigma  lam0   psi   N 
    Mean   130.43594323 14.5319368 0.3361405211 335.8042733 
    SD    7.28386725 9.7311139 0.2743725813 274.6828277 
    Naive SE   0.01329846 0.0177665 0.0005009335 0.5014999 
    Time-series SE 1.28032869 1.3886577 0.0360607870 36.5692414 
    2.5%   118.37718370 0.6129902 0.0300165600 30.0000000 
    25%   124.29743884 5.7535456 0.0958156210 95.0000000 
    50%   130.40628214 15.1264454 0.2426328827 242.0000000 
    75%   135.99836262 19.9685209 0.5403864215 541.0000000 
    97.5%   145.11615201 34.9438198 0.9298185748 930.0000000 
    Point est.  1.59559993 4.4590599 1.0677998255 1.0678381 
    Upper C.I.  2.56854388 9.5792520 1.2186078069 1.2186933 

但是,當我嘗試運行所有輸出文件通過函數使用循環我得到一個NULL輸出。

scrUN.output <- rbind(
     for (i in seq_along(scrUN.lst)){ 
     get_scrUN_output(get(scrUN.lst[i])) 
     } 
    ) 


    >scrUN.output 
    NULL 

謝謝!

回答

0

我認爲這是你要求的。這是最終代碼部分的編輯。因爲沒有任何東西被for循環返回,所以你在使用rbind。

scrUN.output <- lapply(scrUN.lst, function(i) get_scrUN_output(get(i))) 
scrUN.output <- do.call(rbind, scrUN.output) 
scrUN.output 
+0

完美的作品!謝謝。 – JoB

1

原因是你rbind-什麼也沒有。

下面是一個簡化的例子,演示了你的代碼正在做什麼 - for循環沒有給變量分配任何東西,這就是爲什麼你最終得到NULL

xx <- rbind( 
    for(i in c(1,2)){ 
     i 
    } 
) 
print(xx) # NULL 

試試這個:

scrUN.output <- list() # initialize a list 
for (i in seq_along(scrUN.lst)){ 
    # update the list contents 
    scrUN.output[[i]] <- get_scrUN_output(get(scrUN.lst[i])) 
} 
# finally, rbind eveything 
scrUN.output <- do.call(rbind, scrUN.output) 

或者更好的,使用lapply

scrUN.output <- lapply(scrUN.lst, get_scrUN_output) 
scrUN.output <- do.call(rbind, scrUN.output)