【问题标题】:Multiple loop Syntax Error多循环语法错误
【发布时间】:2017-07-09 21:45:45
【问题描述】:

我无法弄清楚我的循环出了什么问题,而且对于我目前的级别来说已经太复杂了。我已经尝试过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'

【问题讨论】:

  • 我没有看过你所有的代码,但你可以先把get(as.matrix(indeces[i]))改成as.matrix(get(indeces[i]))
  • 调试建议:将browse()放在错误发生前的位置。顺便说一句:最终for (i in 1:length(indeces)) 等同于for (i in 1:nrow(as.array(indeces)))
  • 感谢您的 cmets。我会修复它们并编辑我的帖子。

标签: r loops for-loop syntax-error


【解决方案1】:

感谢@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)

如果有一种方法可以更有效地编写它,我将不胜感激。非常感谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 2019-01-19
    相关资源
    最近更新 更多