使用tostring聚合字符串并在r中计算它们

时间:2017-02-22 08:41:17

标签: r dplyr

我在应用dplyr代码后获得了以下数据框

Final_df<- df   %>%
    group_by(clientID,month) %>%
    summarise(test=toString(Sector)) %>%
    as.data.frame()

这给了我以下输出

  ClientID       month          test
   ASD            Sep       Auto,Auto,Finance
   DFG            Oct       Finance,Auto,Oil

我想要的是计算扇区

  ClientID       month          test
   ASD            Sep      Auto:2,Finance:1
   DFG            Oct      Finance:1,Auto:1,Oil:1

如何使用dplyr实现它?

2 个答案:

答案 0 :(得分:4)

这是@akrun的一个类似但略有不同的解决方案:

count(df, ClientID, month, Sector) %>% 
  summarise(test = toString(paste(Sector, n, sep=":")))
#Source: local data frame [4 x 3]
#Groups: ClientID [?]
#
#  ClientID month              test
#     <chr> <chr>             <chr>
#1     ASD.   Oct         Finance:2
#2     ASD.   Sep Auto:2, Finance:1
#3     DFG.   Oct             Oil:2
#4     DFG.   Sep Auto:1, Finance:2

在这种情况下,countgroup_by + tally的效果相同,而您不需要其他group_by,因为count删除了最外层Sector自动分组变量(<meta charset="utf-8" /> )。

答案 1 :(得分:1)

我们可以尝试

df %>% 
    group_by(client_id, month, Sector) %>%
    tally() %>%
    group_by(client_id, month) %>%
    summarise(test = toString(paste(Sector, n, sep=":")))

或使用data.table

library(data.table)
setDT(df)[, .N, .(ClientID, month, Sector)
    ][, .(test = toString(paste(Sector, N, sep=":"))) , .(ClientID, month)]

如果我们需要base R

aggregate(newCol~ClientID + month, transform(aggregate(n~., 
    transform(df, n = 1), sum), newCol = paste(Sector, n, sep=":")), toString)

数据

df <- data.frame(ClientID = rep(c("ASD.", "DFG."), each = 5),
         month = rep(c("Sep", "Oct" ) , c(3,2)),
         Sector = c("Auto", "Auto", "Finance", "Finance", "Finance", 
         "Auto", "Finance", "Finance", "Oil", "Oil"),
        stringsAsFactors=FALSE)