2017-02-20 153 views
0

我無法弄清楚我的循環出了什麼問題,它對我目前的水平來說已經太複雜了。我已經嘗試apply,但顯然我做錯了什麼,所以我根本沒有使用它。多循環語法錯誤

library('wavelets') 
library('benford.analysis') 

indeces <- ls() # my initial datasets 
wfilters <- array(c("haar","la8","d4","c6")) # filter option in "modwt" function 
wfiltname <- array(c("h","l","d","c")) # to rename the new objects 

for (i in 1:nrow(as.array(indeces))) { 
    x <- get(as.matrix(indeces[i])) 
    x <- x[,2] 
    # Creates modwt objects equal to the number of filters 
    for (j in 1:nrow(as.array(wfilters))) { 
    x <- wavelets::modwt(x, filter = wfilters[j], n.levels = 4, 
         boundary = "periodic") 
    # A loop that creates a matrix with benford fun output per modwt n.levels option 
    for (l in 1:4) { 
     x <- as.matrix([email protected]$W[l]) # n.levels are represented as [email protected]$W1, [email protected]$W2,... 
     x <- benford.analysis::benford(x, number.of.digits = 1, 
            sign = "both", discrete = T, 
            round = 3) # accepts matrices 
     x[,l] <- x$bfd$data.dist # it always has 9 elements 
    } 
    assign(paste0("b", wfiltname[j], indeces[i]), x) 
    } 
} 

上面的循環應該可以重現任何數據(其中的值在第二列)。我得到的錯誤如下:

Error in array(x, c(length(x), 1L), if (!is.null(names(x))) list(names(x), : 
    'data' must be of a vector type, was 'NULL' 
+0

我沒有去過你所有的代碼,但你可以通過將'get(as.matrix(indeces [i]))'改成'as.matrix(get(indeces [i])) '。 – Cath

+0

調試建議:在發生錯誤之前將'browse()'放在一個地方。順便說一句:最終'for(我in 1:length(indeces))'相當於'for(i in 1:nrow(as.array(indeces)))' – jogo

+0

感謝您的評論。我會修復他們,我會編輯我的帖子。 –

回答

0

感謝@Cath和@jogo我做了一些改進後,它的工作。這裏是正確的代碼:

temp <- list.files(path = "...") 
list2env(
    lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))), 
     read.csv), envir = .GlobalEnv) 
rm(temp) 

indeces <- ls() 
wfilters <- array(c("haar","la8","d4","c6")) 
wfiltname <- array(c("h","l","d","c")) 
k <- data.frame(matrix(nrow = 9,ncol = 4)) 
nlvl <- 4 

for (i in 1:length(indeces)) { 
    x <- as.matrix(get(indeces[i])) 
    for (j in 1:length(wfilters)) { 
    y <- wavelets::modwt(as.matrix(x), filter = wfilters[j], n.levels = nlvl, 
         boundary = "periodic") 
    y <- as.matrix([email protected]) 
    for(m in 1:nlvl) { 
     z <- as.matrix(y[[m]]) 
     z <- benford.analysis::benford(z, number.of.digits = 1, sign = "both", discrete = TRUE, round = 16) 
     k[m] <- as.data.frame(z$bfd$data.dist) 
     colnames(k)[m] <- paste0(wfilters[j], "W", m) 
    } 
    assign(paste0(indeces[i], wfiltname[j]), k) 
    } 
} 
rm(x,y,z,i,j,m,k) 

我希望如果有一種方法可以更有效地編寫它。非常感謝你