简体   繁体   中英

Format and export the output of Mann-Kendall test in R to excel from Rstudio

I've just started using R and would like to use the trend package to perform Mann-Kendall tests on yearly groundwater level data of multiple wells. Here is a sample from my dataframe pri.csv :

dput(head(GL, 10))
structure(list(WLCODE = structure(c(8L, 5L, 3L, 6L, 1L, 7L, 18L, 
19L, 20L, 22L), .Label = c("W04039", "W04295", "W04299", "W04790", 
"W04791", "W04797", "W04799", "W04824", "W25293", "W25298", "W25355", 
"W25385", "W25404", "W25438", "W25445", "W25451", "W25476", "W25596", 
"W25598", "W25599", "W25600", "W25612", "W25697", "W31151", "W31152"
), class = "factor"), YEAR_OBS = c(2018L, 2018L, 2018L, 2018L, 
2018L, 2018L, 2018L, 2018L, 2018L, 2018L), POMRB = c(4.14, 9.05, 
8.87, 2.3, 6.05, 3.6, 2.05, 4.27, 7.9, 8.4)), .Names = c("WLCODE", 
"YEAR_OBS", "POMRB"), row.names = c(NA, 10L), class = "data.frame")

Here is what I've done so far:

mydata<-read.csv("pri.csv")
sp <- split(mydata, mydata$WLCODE)
results_list <- lapply(sp, function(mydata){
  tryCatch(mk.test(mydata[, 3]),
           error = function(e) e)
})
bad <- sapply(results_list, inherits, "error")
results_list[!bad]

Output

$W07792

    Mann-Kendall trend test

data:  DF[, 3]
z = 1.0355, n = 16, p-value = 0.3004
alternative hypothesis: true S is not equal to 0
sample estimates:
       S     varS      tau 
 24.0000 493.3333   0.2000 


$W07793

    Mann-Kendall trend test

data:  DF[, 3]
z = -0.68205, n = 20, p-value = 0.4952
alternative hypothesis: true S is not equal to 0
sample estimates:
          S        varS         tau 
-22.0000000 948.0000000  -0.1164037

I want to produce a table using this output and export it to excel with WLCODE in each row and Z , p-value , S , varS , tau value in columns. How can I do that? Please help.

An option would be tidy from broom

library(broom)
library(purrr)
library(trend)
map_dfr(results_list[!bad], tidy)

Or with lapply from base R by extracting the individual components

out <- do.call(rbind, lapply(results_list[!bad], function(x) 
  cbind(data.frame(p.value =  x$p.value, statistic  = x$statistic), 
          data.frame(as.list(x$estimates)))))
row.names(out) <- NULL


out
#    p.value statistic  S     varS        tau
#1 1.0000000  0.000000  1 3.666667  0.3333333
#2 1.0000000  0.000000  1 3.666667  0.3333333
#3 0.2962699 -1.044466 -3 3.666667 -1.0000000
#4 1.0000000  0.000000 -1 3.666667 -0.3333333

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM