Regression results

#Reprex Example
library(tidyverse)
library(broom)

# I do a groupwise regression
res1<- mtcars %>% group_by(cyl) %>% group_modify(.f= ~tidy(lm(mpg~disp,data = .x)))

# I try to get the results in a wider form
res2<- res1 %>% pivot_wider(names_from = c(cyl),names_repair = "minimal",
                  values_from = c("estimate","p.value"),-c(std.error,statistic))


res2
#> # A tibble: 2 x 7
#>   term        estimate_4 estimate_6 estimate_8  p.value_4 p.value_6 p.value_8
#>   <chr>            <dbl>      <dbl>      <dbl>      <dbl>     <dbl>     <dbl>
#> 1 (Intercept)     40.9     19.1        22.0    0.00000120   0.00124 0.0000259
#> 2 disp            -0.135    0.00361    -0.0196 0.00278      0.826   0.0568

Created on 2021-04-17 by the reprex package (v2.0.0)

My issue is I want the estimate term and p value term to be together

Intent is unclear; here's one possibility

suppressPackageStartupMessages({
  library(broom)
  library(dplyr)
  library(tidyr)
})

res1 <- mtcars %>%
  group_by(cyl) %>%
  group_modify(.f = ~ tidy(lm(mpg ~ disp, data = .x)))

res2 <- res1 %>% pivot_wider(
  names_from = c(cyl), names_repair = "minimal",
  values_from = c("estimate", "p.value"), -c(std.error, statistic)
)

res2 %>% 
  filter(term == "disp") %>%
  select(estimate_4,p.value_4,estimate_6,p.value_6,estimate_8,p.value_8)
#> # A tibble: 1 x 6
#>   estimate_4 p.value_4 estimate_6 p.value_6 estimate_8 p.value_8
#>        <dbl>     <dbl>      <dbl>     <dbl>      <dbl>     <dbl>
#> 1     -0.135   0.00278    0.00361     0.826    -0.0196    0.0568

The intend is to keep the estimate and p value always together of different "cyl" types. I knew the select command but that is okay if we have smaller number of columns.

relocate() from {dplyr} will change the position of columns

I understand. But can this be automated? Like if I have say, 4 categories of cyl (based on above example), I would need to do relocate or filter again. Can we write a function that always prints the estimate and p value of a particular category together?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.