【问题标题】:Add rows to a tibble dataframe so that each group has the same number of observation将行添加到 tibble 数据框,以便每个组具有相同数量的观察值
【发布时间】:2021-03-03 21:41:34
【问题描述】:

我的数据是这样的(按group列分组)。

df = data.frame(id=c('1','2','3','1','2','1'),group=c('a','a','a','b','b','c'),
                  value1=c(1,2,3,4,5,6),value2=c(1,2,3,4,5,6),stringsAsFactors=FALSE)
df = group_by(df,group)
df

# A tibble: 6 x 4
# Groups:   group [3]
  id    group value1 value2
  <chr> <chr>  <dbl>  <dbl>
1 1     a          1      1
2 2     a          2      2
3 3     a          3      3
4 1     b          4      4
5 2     b          5      5
6 1     c          6      6

列id 可以采用1,2,3 之间的值。我想做的是为每个group,我想为每个id 设置一行。现在对于b 组,我只有id 1 和2 的行;对于c 组,id 1 只有 1 行。我理想的数据框应该是这样的

# A tibble: 9 x 4
# Groups:   group [3]
  id    group value1 value2
  <chr> <chr>  <dbl>  <dbl>
1 1     a          1      1
2 2     a          2      2
3 3     a          3      3
4 1     b          4      4
5 2     b          5      5
6 3     b         NA     NA
7 1     c          6      6
8 2     c         NA     NA
9 3     c         NA     NA

有什么方法可以有效地做到这一点?

【问题讨论】:

    标签: r dplyr tibble


    【解决方案1】:

    我们可以使用complete扩展数据,然后arrange

    library(dplyr)
    library(tidyr)
    df %>% 
      ungroup %>%
      complete(id, group) %>%
        arrange(group)
    

    -输出

    # A tibble: 9 x 4
    #  id    group value1 value2
    #  <chr> <chr>  <dbl>  <dbl>
    #1 1     a          1      1
    #2 2     a          2      2
    #3 3     a          3      3
    #4 1     b          4      4
    #5 2     b          5      5
    #6 3     b         NA     NA
    #7 1     c          6      6
    #8 2     c         NA     NA
    #9 3     c         NA     NA
     
    

    【讨论】:

    • 嗨,很抱歉我的初始版本不准确。我编辑了这个问题。你能看看吗?有分组时,此解决方案不起作用。谢谢。
    • @YifanZhang 你的新数据需要ungroup 在`完成之前。更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 2019-05-17
    • 2023-02-20
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多