gpt4 book ai didi

r - Melt 和 dcast with/字符串连接

转载 作者:行者123 更新时间:2023-12-04 23:19:05 28 4
gpt4 key购买 nike

假设我有以下 data.frame:

foo <- data.frame(CONTACT_DATE = c(rep(as.Date("2015-09-15"),3), rep(as.Date("2015-09-16"),3)), ISSUE = c("abc", "def", "xyz", "abc", "xyz", "def"), ISSUE_COUNT = c(1000,750,100,1500,200,100), RANK = c(1,2,3,1,2,3))
> foo
CONTACT_DATE ISSUE ISSUE_COUNT RANK
1 2015-09-15 abc 1000 1
2 2015-09-15 def 750 2
3 2015-09-15 xyz 100 3
4 2015-09-16 abc 1500 1
5 2015-09-16 xyz 200 2
6 2015-09-16 def 100 3

我如何从上面转到:
CONTACT_DATE ISSUE_RANK_1 ISSUE_RANK_2 ISSUE_RANK_3
2015-09-15 abc (1000) def (750) xyz (100)
2015-09-16 abc (1500) xyz (200) def (100)

我相信我必须使用 melt & dcast来自 reshape2但我一直无法弄清楚如何。

最佳答案

您可以使用 dplyrtidyr :

library(dplyr)
library(tidyr)

foo %>%
mutate(ISSUE_COUNT = paste0("(", ISSUE_COUNT, ")"),
RANK = paste0("ISSUE_RANK_", RANK)) %>%
unite(VAR, ISSUE, ISSUE_COUNT, sep = " ") %>%
spread(RANK, VAR)

这使:
#  CONTACT_DATE ISSUE_RANK_1 ISSUE_RANK_2 ISSUE_RANK_3
#1 2015-09-15 abc (1000) def (750) xyz (100)
#2 2015-09-16 abc (1500) xyz (200) def (100)

关于r - Melt 和 dcast with/字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32596519/

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