[英]How do you perform Mann-kendall test on multiple stations using loops?
我刚开始使用 R,想使用 modifiedmk 包对每月地下水位数据进行测试。 我的数据框(GL)看起来像这样
GL
well year month value
684 1994 Jan 8.53
684 1995 Jan 8.74
684 1996 Jan 8.88
684 1997 Jan 8.24
1001 2000 Jan 9.1
1001 2001 Jan 9.2
1001 2002 Jan 9.54
1001 2003 Jan 9.68
2003 1981 Jan 55.2
2003 1982 Jan 55.8
2003 1983 Jan 56.4
2003 1984 Jan 53.2
首先,我创建了一个井列表和一个 results_list 文件,用于打印结果
well_list <- unique(GL$well)
results_list <- vector("list", length(well_list))
然后我创建了我认为是一个循环
for(i in well_list){
results_list[[grep(i, well_list)]] <- MannKendall(GL[,4])
}
names(results_list) <- well_list
但我一直收到这个错误
Error in Kendall(1:length(x), x) : length(x)<3
我可以让这段代码工作(我从这里的另一篇文章中获取)但我不想执行预白化方法
for(i in well_list){
tempDF <- GL1[GL$well == i, ]
c<-acf(tempDF$value,lag.max=1)
t <- dim(c$acf)
tempDF$prewhit1<-c$acf[[t[1], t[2], t[3]]]*tempDF$value
prewhitseries<-data.frame(with(tempDF,(tempDF$value[-1] - prewhit1[
length(prewhit1)])))
autocordata<-cbind(tempDF[-1,],prewhitseries)
results_list[[grep(i, well_list)]] <- MannKendall(autocordata[,5])}
names(results_list) <- well_list
这样的事情应该做。 split()
沿着分裂well
柱,创建与每个孔的向量的列表。 只保留长度为 3 或更多的向量。 MannKendall()
然后,在每个使用剩余矢量的运行lapply()
library(Kendall)
tt <- read.table(text="
well year month value
684 1994 Jan 8.53
684 1995 Jan 8.74
684 1996 Jan 8.88
684 1997 Jan 8.24
1001 2000 Jan 9.1
1001 2001 Jan 9.2
1001 2002 Jan 9.54
1001 2003 Jan 9.68
2003 1981 Jan 55.2
2003 1982 Jan 55.8
2003 1983 Jan 56.4
2003 1984 Jan 53.2
2004 1984 Jan 53.2", header=TRUE)
tt.wells <- split(tt$value, tt$well)
tt.wells <- tt.wells[lengths(tt.wells) >= 3]
lapply(tt.wells, MannKendall)
# $`684`
# tau = 0, 2-sided pvalue =1
# $`1001`
# tau = 1, 2-sided pvalue =0.089429
# $`2003`
# tau = 0, 2-sided pvalue =1
也许使用split/lapply
更容易,更易读。
首先,运行测试。
sp <- split(GL, GL$well)
results_list <- lapply(sp, function(DF){
tryCatch(MannKendall(DF[, 4]),
error = function(e) e)
})
现在,得到好的,没有错误。
bad <- sapply(results_list, inherits, "error")
并检查它们。
results_list[bad]
#named list()
results_list[!bad]
#$`684`
#tau = 0, 2-sided pvalue =1
#
#$`1001`
#tau = 1, 2-sided pvalue =0.089429
#
#$`2003`
#tau = 0, 2-sided pvalue =1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.