reprex showing correct output but rstudio console is showing error

83 Views Asked by At
library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.6.3
#> Warning: package 'ggplot2' was built under R version 3.6.3
#> Warning: package 'tidyr' was built under R version 3.6.3
#> Warning: package 'purrr' was built under R version 3.6.3
#> Warning: package 'dplyr' was built under R version 3.6.3
#> Warning: package 'stringr' was built under R version 3.6.3
#> Warning: package 'forcats' was built under R version 3.6.3
mtcars = as_tibble(mtcars)
cars_nested = mtcars %>% group_by(cyl) %>% nest()

cars_fitted = cars_nested %>% 
  mutate(fit = map(data, function(x) lm(mpg ~ disp, data = x)))

Created on 2020-07-29 by the reprex package (v0.3.0)

When I ran this code in Rstudio, I am getting the following errors. Any help?

> mtcars = as_tibble(mtcars)
> cars_nested = mtcars %>% group_by(cyl) %>% nest()
> cars_fitted = cars_nested %>% 
+   mutate(fit = map(data, function(x) lm(mpg ~ disp, data = x)))
Error: Problem with `mutate()` input `fit`.
x object 'disp' not found
i Input `fit` is `map(data, function(x) lm(mpg ~ disp, data = x))`.
i The error occured in group 1: cyl = 4.
Run `rlang::last_error()` to see where the error occurred. ```
1

There are 1 best solutions below

0
On

Thanks for the suggestions. I found why I am getting these errors. In the earlier code, I unknowingly nested the mtcars to the same mtcars dataset. So there are only cyl and data columns. Thats why I got the error.