汇总和分发数据

时间:2019-06-03 11:04:43

标签: r tidyverse

我的数据类似于以下内容:

df=data.frame(
company=c("McD","McD","McD","KFC","KFC"),
Title=c("Crew Member","Manager","Trainer","Crew Member","Manager"),
Manhours=c(12,NA,5,13,10)
)
df

我希望对其进行操作并获得如下数据框:

 df=data.frame(
   company=c("KFC", "McD"),
   Manager=c(1,1),
   Surbodinate=c(1,2),
   TotalEmp=c(2,3),
   TotalHours=c(23,17)  
  )

我设法对员工及其人数进行了如下分类:

df<- df %>%
   mutate(Role = if_else((Title=="Manager" ),
                         "Manager","Surbodinate"))%>%  
   count(company,  Role) %>%  
   spread(Role, n, fill=0)%>%
   as.data.frame() %>%
   mutate(TotalEmp= select(., Manager:Surbodinate) %>% 
       apply(1, sum, na.rm=TRUE))

此外,我将工时总结如下:

df <- df %>%group_by(company) %>%
    summarize(TotalHours = sum(Manhours, na.rm = TRUE))

我如何一次将这两个步骤结合在一起,或者有一种更干净/更简单的方式来获得所需的输出?

3 个答案:

答案 0 :(得分:4)

dplyr解决方案:

all_files %>% 
  mutate(filename = str_remove(filename, "C:/Users/AppData/Local/Temp/RtmpkdmJCE/"))

答案 1 :(得分:2)

这样的事情怎么样:

df %>%
  mutate(Role = ifelse(Title=="Manager" ,
                        "Manager", "Surbodinate"))%>%  
  group_by(company) %>% 
  mutate(TotalEmp = n(), 
         TotalHours = sum(Manhours, na.rm=TRUE)) %>%  
  reshape2::dcast(company + TotalEmp + TotalHours ~ Role)

答案 2 :(得分:1)

这不是tidyverse,也不是一个一步的过程。但是,如果您使用data.table,则可以:

library(data.table)
setDT(df, key = "company")

totals <- DT[, .(TotalEmp = .N, TotalHours = sum(Manhours, na.rm = TRUE)), by = company]
dcast(DT, company ~ ifelse(Title == "Manager", "Manager", "Surbodinate"))[totals]

#   company Manager Surbodinate TotalEmp TotalHours
# 1     KFC       1           1        2         23
# 2     McD       1           2        3         17