【问题标题】:How to put several values in one row when use reshape in R? [duplicate]在 R 中使用 reshape 时如何将多个值放在一行中? [复制]
【发布时间】:2016-06-13 03:41:52
【问题描述】:

我有一个这种格式的框架

 "x" "y"
1 A text1
2 A text2
3 A text3
4 B text4
5 B text4
6 B text5
7 C text6

而我需要变成这样:

 "x" "y"    
1 A text1;text2;tex3
2 B text4;text5
3 C text6

可能可以通过 reshape 或 recast 来完成,但我不确定如何将文本值保持在同一行中。 谢谢!

【问题讨论】:

  • @thelatemail 很好,答案更笼统(处理多列)。使用paste(., collapse=";") 的一个答案可能会回答这个问题。
  • 谢谢两位。有时很难将一个想法从西班牙语转换为英语,而这会导致在论坛的其余部分中进行更困难的搜索。下次我会更加小心。

标签: r reshape


【解决方案1】:

我们可以使用data.table

library(data.table)
setDT(df1)[, .(y= toString(y)), by = x]

【讨论】:

    【解决方案2】:

    您可以使用dplyr 执行此操作,如下所示:

    library(dplyr)
    
    ### Data is set from "dput" output.
    data_xy <- structure(list(x = c("A", "A", "A", "B", "B", "B", "C"), y = c("text1", "text2", "text3", "text4", "text4", "text5", "text6")), class = "data.frame", .Names = c("x", "y"), row.names = c(NA, -7L))
    data_xy %>%
        group_by(x) %>%
        summarise(y = paste(unique(y), collapse=";"))
    
    ##   x                 y
    ## 1 A text1;text2;text3
    ## 2 B       text4;text5
    ## 3 C             text6
    
    ## OR
    
    data_xy %>%
        group_by(x) %>%
        summarise_each(funs(paste(unique(.), collapse=";")))
    

    由于您的输出显示text4 仅出现一次B,因此使用unique

    【讨论】:

      猜你喜欢
      • 2017-10-06
      • 2021-11-15
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多