You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言raster函数报错:argument is of length zero 技术求助

R语言RSAGA处理雪崩潜在释放区域报错解决

报错核心原因

两个错误的根源都是**list.files未找到匹配的.asc文件**,返回了长度为0的空向量,传给raster()等函数时触发参数为空的报错:

  1. 第一个错误:执行rugg <- raster(f)时,f是空向量,raster内部判断逻辑因参数长度为0报错
  2. 第二个错误:同样是找不到slope{i_max}.asc文件,raster(f)执行失败,导致as.matrix无法处理空值

解决步骤

  • 确认工作目录:运行getwd()查看当前工作路径,确保和存放ruggedness、slope系列.asc文件的文件夹一致,不一致则用setwd("你的文件所在绝对路径")切换。
  • 检查文件名匹配:
    • 手动核对是否存在ruggedness{i_max}.asc和slope{i_max}.asc文件,注意i_max的数值是否和文件名中的数字完全一致,有没有拼写错误(比如ruggedness漏写字母、大小写不匹配)。
    • 如果文件名后缀是大写.ASC,在list.files里添加ignore.case=TRUE参数,示例:
      f <- list.files(pattern=paste("ruggedness", i_max, ".asc$", sep=""), full.names=TRUE, ignore.case=TRUE)
      
  • 调试文件查找:单独执行list.files语句,查看返回结果。如果返回空,调整pattern参数,比如去掉结尾的$(可能文件名后还有其他字符),或者用更宽松的匹配模式,比如paste0("ruggedness.*", i_max, ".*\\.asc")。
  • 添加空值判断:在调用raster前先检查文件是否找到,避免报错,示例:
    f <- list.files(pattern=paste("ruggedness", i_max, ".asc$", sep=""), full.names=TRUE)
    if (length(f) == 0) {
      stop(paste("未找到目标文件:ruggedness", i_max, ".asc", sep=""))
    }
    rugg <- raster(f)
    

原代码及报错信息

#### Correction of snow surface roughness with slope ####

f <- list.files(pattern=paste("ruggedness", i_max, ".asc$", sep=""), full.names=TRUE)
rugg<- raster(f)
Error in if (x == "" | x == ".") { : argument is of length zero

if (i_max > 1) { 

  f <- list.files(pattern=paste("slope", i_max, ".asc$", sep=""), full.names=TRUE)
  slp_coef <- as.matrix(raster(f))
  slp_coef <- 1- ((slp_coef-30)/30)
  slp_coef[slp_coef < 0] <- 0
  slp_coef[slp_coef > 1] <- 1
  slp_coef <- 1 + (slp_coef * (i_max -1))
  slp_coef <- round(slp_coef, digits = 0)
  #write.ascii.grid(data = slp_coef, "coef", header = head, write.header = TRUE, digits = 2,
  #                hdr.digits = 3 , dec = ".", georef = "corner")


  for (i in 1:(i_max -1)) {
    f <- list.files(pattern=paste("ruggedness", i, ".asc$", sep=""), full.names=TRUE)
    rugg_i<- raster(f)
    rugg[which(slp_coef == i )] <- rugg_i[which(slp_coef == i)]
  }
}
Error in h(simpleError(msg, call)) : 
  error in evaluating the argument 'x' in selecting a method for function 'as.matrix': argument is of length zero

内容的提问来源于stack exchange,提问作者Lizachash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 11:35:13