gpt4 book ai didi

r - 使用 tostring 聚合字符串并在 r 中对它们进行计数

转载 作者:行者123 更新时间:2023-12-01 11:21:23 25 4
gpt4 key购买 nike

应用 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 实现它?

最佳答案

这是与@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)。

关于r - 使用 tostring 聚合字符串并在 r 中对它们进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42386490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com