如何根据数据集列值获取计数结果

时间:2016-02-11 07:43:37

标签: r count multiple-columns

我有以下数据框:

Group   User    Manager Client  Other data1 Other data2
AG  TRUE    TRUE        FALSE       a       b
AG  TRUE    TRUE        FALSE       c       d
JU  FALSE   FALSE       TRUE        d       e
JU  TRUE    TRUE        FALSE       f       g

我想使用像这样的结果:

USER    MANAGER CLIENT  COUNT-AG    COUNT-JU
TRUE    TRUE        FALSE   2       1
FALSE   FALSE       TRUE    0       1

我只能使用以下内容获得一组或另一组的结果:

f = filter(dataframe, Group == “AG”)    
  result <- group_by(f,User,Manager) %>%
    summarize(count=n())

但我无法找到一种方法来获得同一结果中两组的计数。 有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我们可以使用spread中的tidyr来重塑“长期&#39;广泛的&#39;包括&#39; Group&#39;之后的格式也在group_by

library(dplyr)
library(tidyr)
df1 %>% 
   group_by(User, Manager, Client, Group) %>%
   summarise(Count = n()) %>% 
   spread(Group, Count, fill=0)%>%
   rename(COUNT_AG=AG, COUNT_JU=JU) 
 #   User Manager Client  COUNT_AG COUNT_JU  
 #  (lgl)   (lgl)  (lgl)  (dbl)     (dbl)
 #1 FALSE   FALSE   TRUE     0       1
 #2  TRUE    TRUE  FALSE     2       1

如果我们使用data.table,请转换&#39; data.frame&#39;到&#39; data.table&#39; (setDT(df1),并将dcastfun.aggregate一起用作length

 library(data.table)
 dcast(setDT(df1), User+Manager+Client~Group, length)

数据

 df1 <- structure(list(Group = c("AG", "AG", "JU", "JU"), 
 User = c(TRUE, 
 TRUE, FALSE, TRUE), Manager = c(TRUE, TRUE, FALSE, 
 TRUE), Client = c(FALSE, 
 FALSE, TRUE, FALSE), Other_data1 = c("a", "c", "d", 
 "f"), Other_data2 = c("b", 
 "d", "e", "g")), .Names = c("Group", "User", "Manager", 
 "Client", 
 "Other_data1", "Other_data2"), class = "data.frame", 
 row.names = c(NA, -4L))

答案 1 :(得分:0)

正如我在评论中提到的,你必须使用data.table。这是在第一行完成的(+计数由.N完成)。第二行符合您的要求:

yyyy-mm-dd