在简单的 R 脚本中收到 "no such index at level 1" 错误

Receiving "no such index at level 1" error in simple R script

当我运行以下R代码块时:

require(openair)
require(png)

topDir <- "C:/Users/djh/Desktop/WindRoses"
subdirs <- c("Abbotsford_Observations") #, "Vancouver_Observations", "Abbotsford_Modelled", "Vancouver_Modelled")
years <- c(1985) #, 1995, 2001, 2006)

for(i in 1:length(subdirs)){
  for(j in 1:length(years)){
    wd <- paste(topDir, subdirs[i], years[j], sep="/")
    files <- list.files(wd, pattern = "\.out$")
    for(k in 1:length(files)){
      theData <- data.frame(read.table(paste(wd, files[k], sep="/"), header = TRUE, sep=""))
      u <- theData$U10
      v <- theData$V10

      theData["windSpd"] <- sqrt(u^2 + v^2)
      theData["windDir"] <- (270 - (atan2(u/theData$windSpd, v/theData$windSpd)*(180/pi)))

      nameSplit <- strsplit(files[k], ".")

      png(file=paste(wd, "/", nameSplit[[1]], ".png", sep = ""))
      windRose <- windRose(theData, theData$windSpd, theData$windDir, angle = 22.5)
      dev.off()
    }
  }
}

我收到错误:

"Error in .subset2(x, i, exact = exact) : no such index at level 1" after the entire code has been run

查看堆栈交换中此错误的其他实例,似乎它可能与 files[k] 的字符串拆分有关,但 none 的答案已经解决了我的问题。

注意:我试过在nameSplit上使用unlist,但没有解决问题。

我尝试拆分的字符串示例是:

wrfout_d04_1985-07-16.ts.abbotsford.out

这绝对是错误发生的地方,还是脚本中其他地方有明显的原因?

我认为在用于拆分文件名的正则表达式定义中,点应该被双反斜杠屏蔽,就像在分配 files 变量的行中所做的那样。此外,如果您之后想要 select 拆分字符串的第一部分 nameSplit[1].

,则 unlist() 命令可能会有用

因此我建议您使用

nameSplit <- unlist(strsplit(files[k], "\."))

看看问题是否仍然存在。

希望对您有所帮助。

问题实际上来自不同的线路。 openair 包中的 windRose 命令要求在下一行中输入风速和风向,而不是它们在原始问题中的显示方式。

wind_rose <- windRose(theData, ws="windSpd", wd="windDir", angle = 22.5)