【发布时间】:2019-06-28 12:02:34
【问题描述】:
让我们假设在世界上的大量点的每月时间步长上有一个大型气候数据集。然后数据集被塑造成data.frame的类型:
经度、纬度、data_month_1_yr_1、...、data_month_12_yr_100
例子:
set.seed(123)
data<- data.frame(cbind(runif(10000,-180,180), runif(10000,-90,90))
, replicate(1200, runif(10000,0,150)))
我想对每个空间点的每月时间序列执行 Mann-Kendall 检验(使用trend::mk.test),并在data.frame 中获取主要统计数据。为了加快这个漫长的过程,我并行化了我的代码并编写了如下内容:
coords<-data[,1:2] #get the coordinates out of the initial dataset
names(coords)<-c("lon","lat")
data_t<- as.data.frame(t(data[,3:1202])) #each column is now the time series associated to a point
data_t$month<-rep(seq(1,12,1),100) # month index as last column of the data frame
# start the parallel processing
library(foreach)
library(doParallel)
cores=detectCores() #count cores
cl <- makeCluster(cores[1]-1) #take all the cores minus 1 not to overload the pc
registerDoParallel(cl)
mk_out<- foreach(m=1:12, .combine = rbind) %:%
foreach (a =1:10000, .combine = rbind) %dopar% {
data_m<-data_t[which(data_t$month==m),]
library(trend) #need to load this all the times otherwise I get an error (don't know why)
test<-mk.test(data_m[,a])
mk_out_temp <- data.frame("lon"=coords[a,1],
"lat"=coords[a,2],
"p.value" = as.numeric(test$p.value),
"z_stat" = as.numeric(test$statistic),
"tau" = as.numeric(test$estimates[3]),
"month"= as.numeric(m))
mk_out_temp
}
stopCluster(cl)
head(mk_out)
lon lat p.value z_stat tau month
1 -76.47209 -34.09350 0.57759040 -0.5569078 -0.03797980 1
2 103.78985 -31.58639 0.64436238 0.4616081 0.03151515 1
3 -32.76831 66.64575 0.11793238 1.5635113 0.10626263 1
4 137.88627 -30.83872 0.79096910 0.2650524 0.01818182 1
5 158.56822 -67.37378 0.09595919 -1.6647673 -0.11313131 1
6 -163.59966 -25.88014 0.82325630 0.2233588 0.01535354 1
这运行得很好,并给出了我所追求的:一个矩阵报告每个坐标和月份组合的 M-K 统计数据。尽管过程是并行的,但是计算仍然需要相当长的时间。
有没有办法加快这个过程?有使用applyfamily 功能的空间吗?
【问题讨论】:
-
R再次要求调用foreach循环内的库的原因与stackoverflow.com/questions/4765256/… 这个问题有关
标签: r parallel-processing