0

I want to count the number of job positions in the position variable. I know how to do this but since I want to do the same thing with many other variables I thought the easiest thing to do would be to write a function (which I don't really know how to do). I start out with:

PositionCount <- HRdata %>% 
              count(Position, sort = T) %>% 
              mutate(Position = factor(Position)) %>% 
              mutate(Position = fct_reorder(Position, n))

> PositionCount
# A tibble: 32 x 2
   Position                     n
   <chr>                    <int>
 1 Production Technician I    137
 2 Production Technician II    57
 3 Area Sales Manager          27
 4 Production Manager          14
 5 Software Engineer           10
 6 IT Support                   8
 7 Data Analyst                 7
 8 Database Administrator       5
 9 Network Engineer             5
10 Sr. Network Engineer         5
# ... with 22 more rows

I want to do the same thing with some other variables and I wrote the function:

 HRdata_factor_count <- function(x) {
  HRdata %>% 
  count(x, sort = T) %>% 
  mutate(x = factor(x)) %>% 
  mutate(x = fct_reorder(x, n))
 }

  Error: Must group by variables found in `.data`.
* Column `x` is not found.

How can I rewrite this function so it x properly references the column in my HRdata that I would like to count.

Taren Shaw
  • 89
  • 6
  • How exactly are you calling your `HRdata_factor_count` function? If you are doing `HRdata_factor_count(Position)`. Then do things like `HRdata %>% count({{x}}, sort = T)` in your function – MrFlick Apr 27 '21 at 20:58
  • 1
    [this](https://dplyr.tidyverse.org/articles/programming.html) is a very good place to start learning how to program with dplyr – Onyambu Apr 27 '21 at 21:00

0 Answers0