Linear regression by rows

You can use this example as starting point

library(dplyr)
library(tidyr)
library(purrr)
library(broom)

data <- data.frame(stringsAsFactors=FALSE,
                   ITEM = c("item A", "item B"),
                   JAN = c(10, 30),
                   FEB = c(20, 35),
                   MAR = c(15, 37),
                   APR = c(17, 38)
                   )

fit_model <- function(df) lm(value ~ n, data = df)
get_slope <- function(mod) tidy(mod)$estimate[2]

data %>% 
    gather('month', 'value', -ITEM) %>% 
    group_by(ITEM) %>% 
    mutate(n = row_number()) %>% 
    arrange(ITEM, n) %>% 
    nest() %>% 
    mutate(model = map(data, fit_model)) %>% 
    mutate(slope = map_dbl(model, get_slope))
#> # A tibble: 2 x 4
#>   ITEM   data             model    slope
#>   <chr>  <list>           <list>   <dbl>
#> 1 item A <tibble [4 x 3]> <S3: lm>  1.6 
#> 2 item B <tibble [4 x 3]> <S3: lm>  2.60

Created on 2019-01-12 by the reprex package (v0.2.1)

5 Likes