Tpellirn
Tpellirn

Reputation: 796

How to apply a function to several categories in a data.frame?

I have this data.frame:

library(trend)
 Data=structure(list(Year = structure(c(-25567, -25202, -24837, -24472, 
-24107, -23741, -23376, -23011, -22646, -22280, 10592, 10957, 11323, 11688, 12053, 
 12418, 12784, 13149, 13514, 13879, 14245, 14610, 14975, 15340, 15706, 16071, -25567, 
-25202, -24837, -24472, -24107, -23741, -23376, -23011, -22646, -22280), class = 
"Date"),     variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("TT", 
"CC"), class = "factor"), Mean = c(1,   7, 4, 3,8, 3, 6, 7, 5, 3, 4, 6, 3, 1, 13, 4, 
18, 14, 16, 16, 17, 15, 15, 74, 19, 19, 0, 5, 18, 0.5, 3, 7, 0., 0, -1, -2), par = 
c("h",     "h", "h", "h", "h", "h", "h", "h",     "h", "h", "h", "h", "h", "h", "h",     
"h", "h", "h", "m", "m", "m", "m",     "m", "m", "m", "m", "h", "h", "h",     "h", 
"h", "m", "m", "m", "m", "m"    )), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 
10L,100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 
111L, 112L, 113L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 
122L, 123L, 124L, 125L), class = "data.frame")

I want to compute the sen's slope function for all parameters in 'par' and their corresponding variables in 'variable', so I will have 4 results for

 h TT   sens slop >>>
 h cc   sens slop >>>
 m TT   sens slop >>> 
 m cc   sens slop >>>

I want to apply the `sens.slope` function.

Upvotes: 1

Views: 54

Answers (1)

akrun
akrun

Reputation: 887108

We can group by and apply the function, store the output in a list

library(dplyr)
library(trend)
Data %>%
   group_by(variable, par) %>% 
   summarise(Slope = list(sens.slope(Mean)), .groups = 'drop')

-output

# A tibble: 4 x 3
#  variable par   Slope  
#* <fct>    <chr> <list> 
#1 TT       h     <htest>
#2 TT       m     <htest>
#3 CC       h     <htest>
#4 CC       m     <htest>

If we want to return the 'statistic', extract it from the list output of sens.slope

Data %>%
   group_by(variable, par) %>% 
   summarise(Slope = sens.slope(Mean)$statistic, .groups = 'drop')
# A tibble: 4 x 3
#  variable par    Slope
#* <fct>    <chr>  <dbl>
#1 TT       h      1.15 
#2 TT       m      1.01 
#3 CC       h      0.245
#4 CC       m     -2.02 

Similarly, can extract the pvalue with $p.value

Upvotes: 1

Related Questions