多循环语法错误

时间:2017-02-20 14:46:46

标签: r loops for-loop syntax-error

我无法弄清楚我的循环出了什么问题,而且对于我目前的等级来说已经太复杂了。我已经尝试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(x@W$W[l]) # n.levels are represented as x@W$W1, x@W$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'

1 个答案:

答案 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(y@W)
    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)

如果有办法更有效地写它,我将不胜感激。非常感谢你