'How can I simplify the code using just the tidyverse?

so I have the data frama below, and I'm trying to creat a new Data frame which show me the name of the department which have the highest and the lowest employee turnover. The code that I write is correct, but is too big, so I am wondering how can I simpkly it. Thanks

My data:

df = data.frame(
          department = c("admin", "engineering", "finance", "IT", "logistics", "marketing", "operations", "retail", "sales", "support", "admin", "engineering", "finance", "IT", "logistics", "marketing", "admin", "retail", "admin", "engineering"),
          promoted = c(0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1),
          review = c(0.4, 0.5, 0.4, 0.8, 0.4, 0.1, 0.9, 0.2, 0.1, 0.1, 0.1, 0.7, 0.1, 0.55, 0.4, 0.33, 0.11, 0.1, 0.11, 0.1),
          projects = c(1, 2, 1, 3, 4, 1, 5, 0, 1, 1, 2, 1, 3, 4, 1, 5, 0, 1, 0, 1),
          salary = c("low", "medium", "high", "low", "medium", "low", "medium", "low", "low", "low", "medium", "high", "low", "medium", "low", "medium", "low", "low", "low", "medium"),
          tenure =  c(1, 2, 1, 3, 4, 1, 5, 0, 1, 1, 2, 1, 3, 4, 1, 5, 0, 1, 0, 1),
          satisfaction = c(0.4, 0.5, 0.4, 0.8, 0.4, 0.1, 0.9, 0.2, 0.1, 0.1, 0.1, 0.7, 0.1, 0.55, 0.4, 0.33, 0.11, 0.1, 0.11, 0.1),
          bonus = c(0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1),
          left = c("yes", "no", "yes", "no", "no", "no", "yes", "yes", "no", "yes", "no", "yes", "no", "no", "no", "yes", "yes", "no", "yes", "no"))

My Code:

library(tidyverse)
df1 <- df%>%
   count(department)

colnames(df1) <- c('department','Total')


df2<- df%>%
  filter(left == "yes")%>%
  count(department)

colnames(df2) <- c('department','Yes')



df2$Yes<-as.numeric(df2$Yes)
df1$Total<-as.numeric(df1$Total)


df3 <- inner_join(df1, df2)
head(df3, 10)
  

df3Max <-df3%>%
  mutate( turnover = Yes/Total ) %>%
  arrange(desc(turnover))
df3Max <- head(df3Max, 1)


df3Min <-df3%>%
  mutate( turnover = Yes/Total ) %>%
  arrange(turnover)
df3Min <- head(df3Min, 1)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source