【发布时间】:2017-01-14 15:18:18
【问题描述】:
我需要从光栅堆栈数据中替换或插入每个单元格的向量中的 NA。我有两个函数 fun_sub 用于替换 NA 和 fun_interp 用于插值 NA。 我发现 fun_sub 效果很好。但是 fun_interp 不起作用,但我找不到原因。 非常感谢
张天一
下面是一个简单的例子:
#------EXAMPLE
library(timeSeries)
library(raster)
fun_sub <- function(x) {
# substitute the NA to the mean of vector for each cell
v=as.vector(x)
z<-substituteNA(v,type="mean")
return (z)
}
fun_interp <- function(x) {
# interpolate the NA to the the linear regression of vector for each cell
v=as.vector(x)
z=interpNA(v, method="linear")
return (z)
}
# create data
r<-raster(ncols=2,nrows=2)
r1<-r; r2<-r; r3<-r; r4<-r
r1[]<-c(1,1,1,2)
r2[]<-c(5,5,NA,5)
r3[]<-c(3,3,4,2)
r4[]<-c(6,5,5,2)
s<-stack(r1,r2,r3,r4)
# try the two functions; the task is change the NA in r2 to a number;
res_sub<-calc(s,fun_sub) # works great! substitute the NA to the mean of c(1,NA,4,5); I got c(1,3.333,4,5)
res_inter<-calc(s,fun_interp) # cannot interpolate; have an error, don't know the reason; I expected it is c(1, 2.5 ,4, 5). But it returns an error
# try whether interpNA() can work or not
interpNA(c(1,NA,4,5),method="linear") # but this function is OK.
【问题讨论】:
-
请查看stackoverflow.com/help/mcve,看看您是否可以根据这些准则重写您的问题。您还说“返回错误”-您应该发布它。
标签: time-series r-raster linear-interpolation string-substitution