Search code examples
rexceldataframetrend

How to create dataframe using results (output) of sens.slope function?


I have an Excel data with multiple sheets. I imported them into R and applied Mann-Kendall trend test with the function sens.slope(). The results of this function are in htest class, but I want to put them in a table.

I installed packages needed and imported each sheets of dataset.

require(readxl)
require(trend)
tmin1 <- read_excel("C:/TEZ/ANALİZ/future_projection/2051-2100/model 3-3/average_tmin_3_3_end.xlsx", sheet = "acipayam")
tmin2 <- read_excel("C:/TEZ/ANALİZ/future_projection/2051-2100/model 3-3/average_tmin_3_3_end.xlsx", sheet = "adana")
...
tmin57 <- read_excel("C:/TEZ/ANALİZ/future_projection/2051-2100/model 3-3/average_tmin_3_3_end.xlsx", sheet = "yumurtalik")

Then, specified the columns for trend test.

x1<-tmin1$`13`
x2<-tmin1$`14`
x3<-tmin1$`15`
x4<-tmin1$`16`
x5<-tmin1$`17`
...
x281<-tmin57$`13`
x282<-tmin57$`14`
x283<-tmin57$`15`
x284<-tmin57$`16`
x285<-tmin57$`17`

And appplied the function.

sens.slope(x1)
sens.slope(x2)
sens.slope(x3)
....
sens.slope(x285)

The result is looking like this.

> sens.slope(x1)

    Sen's slope

data:  x1
z = 4.6116, n = 49, p-value = 3.996e-06
alternative hypothesis: true z is not equal to 0
95 percent confidence interval:
 0.03241168 0.08101651
sample estimates:
Sen's slope 
 0.05689083 

> sens.slope(x2)

    Sen's slope

data:  x2
z = 6.8011, n = 49, p-value = 1.039e-11
alternative hypothesis: true z is not equal to 0
95 percent confidence interval:
 0.05632911 0.08373755
sample estimates:
Sen's slope 
 0.07032428 
...

How can I put these values in a single table and write them to an Excel file? (names of needed values are statistic and estimates in the function.)


Solution

  • Try using lists instead of having so many objects in global environment.

    Now since you already have them, you can combine them in a list, apply sens.slope on each one, extract statistic and estimates from them an get the dataframe.

    library(trend)
    
    output <- data.frame(t(sapply(mget(paste0('x', 1:285)), function(y) 
                         {temp <- sens.slope(y);c(temp$statistic, temp$estimates)})))
    

    You can now write this dataframe as csv using write.csv.

    write.csv(output, 'output.csv', row.names = FALSE)