Aggregating strings using tostring and counting them in r

隐身守侯 提交于 2021-01-27 11:53:34

问题


I have following dataframe got after applying dplyr code

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

Which gives me following output

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

How I want is to count sectors as well

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

How can I achieve it with dplyr?


回答1:


We can try

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

Or using data.table

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

If we need a base R

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

data

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) 



回答2:


Here's a similar but slightly different solution to the one by @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

In this case, count does the same as group_by + tally and you don't need another group_by since the count removes the outer most grouping variable (Sector) automagically.



来源:https://stackoverflow.com/questions/42386490/aggregating-strings-using-tostring-and-counting-them-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!