代码之家  ›  专栏  ›  技术社区  ›  T Richard

根据递归行设置数据帧并创建用于排序的列

  •  0
  • T Richard  · 技术社区  · 6 年前

    考虑示例数据

    df <-
      structure(
        list(
          id = c(1L, 1L, 1L, 1L, 2L, 2L, 3L),
          A = c(20L, 12L, 13L, 8L, 11L, 21L, 17L),
          B = c(1L, 1L, 0L, 0L, 1L, 0L, 0L)
        ),
        .Names = c("id", "A", "B"),
        class = "data.frame",
        row.names = c(NA,-7L)
      )
    

    每个ID(存储在列1中)都有不同数量的列条目 A B . 在示例数据中,有四个观测值 id = 1 . 我正在寻找一种方法在R中对这些数据进行子集,以便每个ID最多有3个条目,最后创建另一列(标记为C),该列由每个ID的顺序组成。预期输出如下:

    df <-
      structure(
        list(
          id = c(1L, 1L, 1L, 2L, 2L, 3L),
          A = c(20L, 12L, 13L, 11L, 21L, 17L),
          B = c(1L, 1L, 0L, 1L, 0L, 0L),
          C = c(1L, 2L, 3L, 1L, 2L, 1L)
        ),
        .Names = c("id", "A", "B","C"),
        class = "data.frame",
        row.names = c(NA,-6L)
      )
    

    非常感谢你的帮助。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Matthew Hui    6 年前

    这样地?

    library(data.table)
    dt <- as.data.table(df)
    dt[, C := seq(.N), by = id]
    dt <- dt[C <= 3,]
    dt
    #    id  A B C
    # 1:  1 20 1 1
    # 2:  1 12 1 2
    # 3:  1 13 0 3
    # 4:  2 11 1 1
    # 5:  2 21 0 2
    # 6:  3 17 0 1
    
        2
  •  1
  •   nghauran    6 年前

    这里有一个选择 dplyr 并考虑基于a的前3个值(基于@ronak shah的评论)。

    library(dplyr)
    df %>%
            group_by(id) %>%
            top_n(n = 3, wt = A) %>% # top 3 values based on A
            mutate(C = rank(id, ties.method = "first")) # C consists of the order of each id
    # A tibble: 6 x 4
    # Groups:   id [3]
         id     A     B     C
      <int> <int> <int> <int>
    1     1    20     1     1
    2     1    12     1     2
    3     1    13     0     3
    4     2    11     1     1
    5     2    21     0     2
    6     3    17     0     1