【问题标题】:Grouping variables and adding them to the end of the table分组变量并将它们添加到表的末尾
【发布时间】:2022-11-30 06:21:47
【问题描述】:

我有一个如下所示的表:

Type Number
A 1
B 2
E 3
C 4
D 5
C 6
G 7

我想制作一个表格,将类型 (A-C) 分组并将这些相同的观察结果添加到表格的底部。所以新表看起来像:

Type Number
A 1
B 2
E 3
C 4
D 5
C 6
G 7
A-C 1
A-C 2
E 3
A-C 4
D 5
A-C 6
G 7

这可能吗?任何帮助将非常感激!

【问题讨论】:

    标签: r


    【解决方案1】:

    一种选择是计算出您的分组,然后将两个数据帧绑定在一起,例如

    library(dplyr)
    
    df <- read.table(text = "Type   Number
    A   1
    B   2
    E   3
    C   4
    D   5
    C   6
    G   7", header = TRUE)
    
    tmp <- df %>%
      mutate(Type = ifelse(Type %in% c("A", "B", "C"),
                           "A-C", Type))
    result <- bind_rows(df, tmp)
    result
    #>    Type Number
    #> 1     A      1
    #> 2     B      2
    #> 3     E      3
    #> 4     C      4
    #> 5     D      5
    #> 6     C      6
    #> 7     G      7
    #> 8   A-C      1
    #> 9   A-C      2
    #> 10    E      3
    #> 11  A-C      4
    #> 12    D      5
    #> 13  A-C      6
    #> 14    G      7
    

    创建于 2022-11-30 reprex v2.0.2


    相同的方法,但使用基础 R(即不需要 dplyr 包):

    df <- read.table(text = "Type   Number
    A   1
    B   2
    E   3
    C   4
    D   5
    C   6
    G   7", header = TRUE)
    
    tmp <- df
    tmp$Type <- ifelse(df$Type %in% c("A", "B", "C"), "A-C", df$Type)
    rbind(df, tmp)
    #>    Type Number
    #> 1     A      1
    #> 2     B      2
    #> 3     E      3
    #> 4     C      4
    #> 5     D      5
    #> 6     C      6
    #> 7     G      7
    #> 8   A-C      1
    #> 9   A-C      2
    #> 10    E      3
    #> 11  A-C      4
    #> 12    D      5
    #> 13  A-C      6
    #> 14    G      7
    

    创建于 2022-11-30 reprex v2.0.2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多