【问题标题】:Melt & dcast w/ string concatenationMelt & dcast 带字符串连接
【发布时间】:2015-12-12 07:50:55
【问题描述】:

假设我有以下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)

我相信我必须使用reshape2 中的meltdcast,但我无法弄清楚如何使用。

【问题讨论】:

    标签: r reshape reshape2 melt


    【解决方案1】:

    dcast默认使用输入表的最后一列作为输出表的值。

    library(reshape2)
    d = read.table(text="id 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", header=T)
    d$x = paste(d$ISSUE, paste0("(",d$ISSUE_COUNT,")"))   # create new column with values that will appear in table
    dcast(CONTACT_DATE ~ RANK, data=d)
    

    输出:

      CONTACT_DATE          1         2         3
    1   2015-09-15 abc (1000) def (750) xyz (100)
    2   2015-09-16 abc (1500) xyz (200) def (100)
    

    【讨论】:

    • 你为什么要read.table-ing OP 的输入?第一行实际上给出了输入,foo &lt;- data.frame(...
    【解决方案2】:

    您可以使用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)
    

    【讨论】:

    • @Ray 很高兴它有帮助!
    猜你喜欢
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2014-08-12
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2014-03-31
    相关资源
    最近更新 更多