1

I am trying to reproduce and understand a colleague's code in my system

library(tidyverse)
data <- mtcars

tabl1 <- data %>%
  mutate(cyl = as.character(cyl)) %>%
  bind_rows(mutate(., cyl = "all")) %>%
  group_by(cyl) %>% 
  summarise(mpg_q25 = quantile(mpg, prob = .25),
            mpg_q50 = quantile(mpg, prob = .50),
            mpg_q75 = quantile(mpg, prob = .75),
            count = n())

tabl1

It is supposed to give me the following result:

# A tibble: 4 × 5
  cyl   mpg_q25 mpg_q50 mpg_q75 count
  <chr>   <dbl>   <dbl>   <dbl> <int>
1 4        22.8    26      30.4    11
2 6        18.6    19.7    21       7
3 8        14.4    15.2    16.2    14
4 all      15.4    19.2    22.8    32

However I am ending up with the following error:

Error in `bind_rows()`:
! Can't combine `..1$cyl` <double> and `..2$cyl` <character>.

Can someone explain what am I missing here? Also it would be great help if you can help me understand the syntax of mutate here.

EDIT: tried the answer posted by @akrun which resolved the character issue. However a new error has popped up as below:

no applicable method for 'mutate' applied to an object of class "character"

How do I solve this? Also explain the "." used as first argument of mutate in bind rows?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Varun KV
  • 11
  • 4
  • Can't reproduce. This only happens if you **forget to run the data <- mtcars` line first** ... – Ben Bolker Sep 30 '22 at 21:25
  • In that case, I should not be getting the quantile summary as well. I get the quantile summary following which I get the method error. – Varun KV Sep 30 '22 at 23:37
  • I don't understand/can't reproduce. If I run the code in your question exactly as written (cut-and-paste), in a **clean R session**, I get exactly the results you posted, with no errors. I can appreciate that you're new to SO, but there are a couple of problematic things about this question: (1) it asks multiple questions in the same post; (2) it's a bit of a [chameleon question](https://meta.stackoverflow.com/questions/377812/methods-to-remedy-a-chameleon-question-and-teach-the-op) (the question keeps changing as people point out particular errors in your code) ... – Ben Bolker Sep 30 '22 at 23:50
  • (3) it's not easily reproducible (you did post all the code and the expected answer -- that's good -- but there seems to be something about your environment that's different). What do you get if you run `find("mutate")` ? – Ben Bolker Sep 30 '22 at 23:51
  • 1
    Hi Ben, Thanks for pointing out the issues with my question. I will keep in mind the suggestions you have given for future posts / questions. Also after 2 complete restarts the error seems to have disappeared now due to which I have not run find("mutate") for now. Will update if in case I get any further issues. – Varun KV Oct 01 '22 at 14:22

0 Answers0