【问题标题】:Function raise error with return statement函数使用返回语句引发错误
【发布时间】:2019-06-17 01:14:31
【问题描述】:

我想使用“raster”包的 calc 函数在每个单元格上处理自己设计的函数。

当我尝试打印函数的“最终”结果(我想要返回的值)时,一切正常,但是当我尝试使用 return 语句时,出现错误:

Error in .local(x, values, ...) : 
  values must be numeric, integer or logical.

这是导致该错误的代码

inR <- 'D://test/TS_combined_clipped.tif'
outR <- 'D://test/R_test3.tif'

rasterB <- brick(inR)
fun1 <-function(x){
  years = seq(1, 345)
  na_idx = which(is.na(x))
  years = years[-na_idx]
  x <- na.omit(x)
  idx = detectChangePoint(x, cpmType='Student', ARL0=500)$changePoint
  return(years[idx]) # this raises error
  # print(years[idx]) # This does *not* raises any error
}

r <- calc(rasterB, fun=fun1, filename=outR, overwrite=TRUE)

如何有一个返回语句使其失败?

我的一些测试表明,在 rasterBrick 的最后一个单元格上执行 calc 函数后,该进程似乎失败了。 但我不知道从哪里开始尝试解决这个问题。

Input image is available here

[编辑]

我刚刚注意到,如果我使用return(idx) 而不是return(year[idx]),则该过程可以正常工作而不会引发错误。 因此,问题似乎更多地在于获取 year 变量的值。 因此,我在使用 R 的索引时错过了什么特别的事情吗?

【问题讨论】:

  • 可能存在未检测到更改点的情况。那么idx 将为零,years[idx] 将是长度为零的向量。显然calc() 不喜欢长度为零的向量。或者问题可能是检测到多个变化点。我们没有您的数据,也无法判断。
  • 谢谢!我会检查您的建议,并且有输入数据的链接(帖子结束,“编辑”之前)

标签: r raster calc


【解决方案1】:

user2554330 的评论让我走上了正轨,问题是 calc 无法处理“numeric(0)”结果。

然后更新代码

inR <- 'D://test/TS_combined_clipped.tif'
outR <- 'D://test/R_test3.tif'

rasterB <- brick(inR)
fun1 <-function(x){
  years = seq(1, 345)
  na_idx = which(is.na(x))
  years = years[-na_idx]
  x <- na.omit(x)
  idx = detectChangePoint(x, cpmType='Student', ARL0=500)$changePoint
  if (idx==0){
    return(0)
  } else {
    return(as.integer(years[idx]))
  }
}

r <- calc(rasterB, fun=fun1, filename=outR, overwrite=TRUE)

【讨论】:

    猜你喜欢
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多