user9631425
user9631425

Reputation: 21

Error in as.data.frame.default(data) : cannot coerce class ""formula"" to a data.frame

I'm not quite sure why I'm getting this error or what it means. My data frame is called "data."

  library(dplyr)
  data %>%
  filter(Info==1, Male==1) %>%
  lm(CFL_Purchased ~ Male)  %>% 
  summary()

Thanks!

Upvotes: 2

Views: 14444

Answers (1)

tomasu
tomasu

Reputation: 1438

This worked for me:

library(dplyr)

dat <- data.frame(x = rnorm(10000, 4, 3),
                  y = rnorm(10000, 2, 2))

dat %>%
  lm(y ~ x,.) %>%
  summary()

Call:
lm(formula = y ~ x, data = .)

Residuals:
    Min      1Q  Median      3Q     Max 
-7.5620 -1.3678 -0.0307  1.3625  8.0371 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 1.952941   0.033064  59.065   <2e-16 ***
x           0.008841   0.006617   1.336    0.182    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 2.001 on 9998 degrees of freedom
Multiple R-squared:  0.0001785, Adjusted R-squared:  7.852e-05 
F-statistic: 1.785 on 1 and 9998 DF,  p-value: 0.1815

Edited to add base pipe option:

dat <- data.frame(x = rnorm(10000, 4, 3),
                  y = rnorm(10000, 2, 2))

dat |>
  lm(formula = y ~ x) |>
  summary()

Call:
lm(formula = y ~ x, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max 
-8.6279 -1.3734  0.0017  1.3711  9.1955 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  2.04624    0.03379  60.559   <2e-16 ***
x           -0.01079    0.00675  -1.598     0.11    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.033 on 9998 degrees of freedom
Multiple R-squared:  0.0002555,  Adjusted R-squared:  0.0001555 
F-statistic: 2.555 on 1 and 9998 DF,  p-value: 0.11

Upvotes: 3

Related Questions