littleworth
littleworth

Reputation: 5169

How to use dplyr pipe to perform linear model

I have the following data frame:

library(broom)
library(tidyverse)
dat <- structure(list(x = c(800, 400, 200, 100, 50), y = c(605, 467, 
323, 219, 110)), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame"))
dat

That looks like this:

# A tibble: 5 × 2
      x     y
  <dbl> <dbl>
1   800   605
2   400   467
3   200   323
4   100   219
5    50   110

What I'm trying to do is to fit lm using dplyr piping. When I try this:

fit_conc_df <- dat %>% do(fit_conc = lm(y ~ x, data = .))
glance(fit_conc_df, fit_conc)

I get this message:

Error: There is no glance method for tibbles. Did you mean `tibble::glimpse()`?

What I hope to get is this (without piping):

 x <- c(50, 100, 200, 400, 800)
 y <- c(110, 219, 323, 467, 605)
 conc_fit <- lm(y ~ x)
 glance(conc_fit)

with this result:

# A tibble: 1 × 12
  r.squared adj.r.squared sigma statistic p.value    df logLik   AIC   BIC
      <dbl>         <dbl> <dbl>     <dbl>   <dbl> <dbl>  <dbl> <dbl> <dbl>
1     0.910         0.880  68.0      30.3  0.0118     1  -26.9  59.8  58.7
# … with 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>

Upvotes: 1

Views: 1790

Answers (1)

JaredS
JaredS

Reputation: 240

Keep it simple. Don't overcomplicate.

fit_conc_df <- dat %>% lm(y ~ x, data = .)
fit_conc_df %>% 
  glance()

# A tibble: 1 x 12
  r.squared adj.r.squared sigma statistic p.value    df logLik   AIC   BIC
      <dbl>         <dbl> <dbl>     <dbl>   <dbl> <dbl>  <dbl> <dbl> <dbl>
1     0.910         0.880  68.0      30.3  0.0118     1  -26.9  59.8  58.7
# ... with 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>

The reason your code was failing is because the pipe operator is passing the data as the first argument to the lm() function but you were also providing an argument name fit_conc.

Also, you can create the data frame/tibble much more concisely as follows:

 dat <- tibble(x = c(50, 100, 200, 400, 800), 
               y = c(110, 219, 323, 467, 605)) 

Upvotes: 1

Related Questions