简体   繁体   English

在简单的R脚本中收到“在1级没有这样的索引”错误

[英]Receiving “no such index at level 1” error in simple R script

When I run the following block of R code: 当我运行以下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()
    }
  }
}

I receive the error: 我收到错误:

"Error in .subset2(x, i, exact = exact) : no such index at level 1" after the entire code has been run 在运行了整个代码之后,“。subset2(x,i,精确=精确)中的错误:级别1上没有这样的索引”

Looking at other instances of this error on stack exchange, it seems it might be linked to the string splitting of files[k] , but none of the answers have solved my problem. 在堆栈交换上查看此错误的其他实例,似乎它可能与files[k]的字符串拆分有关,但没有任何答案可以解决我的问题。

Note: I have tried to use unlist on nameSplit and it did not solve the problem. 注意:我试图在unlist上使用nameSplit ,但无法解决问题。

An example of the strings I am trying to split is: 我尝试拆分的字符串的示例是:

wrfout_d04_1985-07-16.ts.abbotsford.out

Is this definitely where the error is occurring or is there an obvious cause elsewhere in the script? 这肯定是发生错误的地方,还是脚本中其他地方的明显原因?

I think that in the regex definition that you use to split the file names the dot should be masked by a double backslash, as it is done in the line where the files variable is assigned. 我认为在用于拆分文件名的正则表达式定义中,点应该用双反斜杠屏蔽,因为在files变量分配所在的行中已完成。 Additionally, an unlist() command might be useful if afterwards you want to select the first part of the split string with nameSplit[1] . 另外,如果之后要使用nameSplit[1]选择拆分字符串的第一部分,则unlist()命令可能会很有用。

I therefore suggest that you use 因此,我建议您使用

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

and see if the problem persists. 并查看问题是否仍然存在。

Hope this helps. 希望这可以帮助。

The issue was coming from a different line actually. 问题实际上出在不同的地方。 The windRose command from the openair package requires wind speed and direction to be entered as they are in the following line, rather than how they appear in the original question. openair软件包中的windRose命令要求在下一行中输入风速和风向,而不是在原始问题中如何显示风速和风向。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM