【问题标题】:How do i count observations within a group for each row? [duplicate]我如何计算组内每一行的观察值? [复制]
【发布时间】:2021-05-14 18:44:30
【问题描述】:

我有一个看起来像这样的数据集

ID|Type
1  "Basketball"
1  "Baseball"
2  "Basketball"
2  "Football"
3  "Boxing"
4  "Boxing"
4  "Wrestling"
4  "Handball"
4  "Hockey"

我想创建一个如下所示的数据集

ID|        Type|observation
1  "Basketball" 1      
1  "Baseball"   2
2  "Basketball" 1
2  "Football"   2
3  "Boxing"     1
4  "Boxing"     1
4  "Wrestling"  2
4  "Handball"   3
4  "Hockey"     4

我在这部分之后被卡住并尝试这样做

 df %>% 
 group_by(ID) %>%
 1:nrow(df)

【问题讨论】:

    标签: r dplyr group-by


    【解决方案1】:

    我们可以使用row_number())(它在我们编辑之前首先发布在这里,唯一的问题是分组包含类型并且之前没有测试它)

    library(dplyr)    
    df %>%
        group_by(ID) %>%
        mutate(observation = match(Type, unique(Type))) %>%
        ungroup
    

    -输出

    # A tibble: 9 x 3
    #     ID Type       observation
    #  <int> <chr>            <int>
    #1     1 Basketball           1
    #2     1 Baseball             2
    #3     2 Basketball           1
    #4     2 Football             2
    #5     3 Boxing               1
    #6     4 Boxing               1
    #7     4 Wrestling            2
    #8     4 Handball             3
    #9     4 Hockey               4
    

    或使用factor

     df %>%
        group_by(ID) %>%
        mutate(observation = as.integer(factor(Type, levels = unique(Type)))) %>%
        ungroup
    

    或者1:n()

     df %>%
        group_by(ID) %>%
        mutate(observation = 1:n())
    

    或使用base R

    df$observation <- with(df, ave(seq_along(ID), ID, FUN = seq_along))
    

    数据

    df <- structure(list(ID = c(1L, 1L, 2L, 2L, 3L, 4L, 4L, 4L, 4L), 
    Type = c("Basketball", 
    "Baseball", "Basketball", "Football", "Boxing", "Boxing", "Wrestling", 
    "Handball", "Hockey")), class = "data.frame", row.names = c(NA, 
    -9L))
    

    【讨论】:

      【解决方案2】:

      您可以使用row_number() 添加组行号。

      df %>% 
        group_by(ID) %>%
        mutate(observation = row_number())
      

      mutate 是通用的dplyr 函数,用于添加或修改列。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多