【问题标题】:Subsetting a data frame and replacing a column based on condition子集数据框并根据条件替换列
【发布时间】:2018-04-29 13:06:24
【问题描述】:

我正在处理一个数据框,其中包含三个标记为 id、time1 和 time2 的列。一个示例是:

df <-
  structure(
    list(
      id = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L),
      time1 = c(12L, 5L, 3L, 5L, 6L, 30L, 3L, 30L, 7L, 2L, 17L, 5L, 8L, 3L, 22L, 5L, 15L, 4L, 7L, 23L),
      time2=c(23L,23L,23L,23L,23L,22L,22L,22L,22L,22L,25L,25L,25L,25L,25L,24L,24L,24L,24L,24L)
    ),
    .Names = c("id", "time1","time2"),
    class = "data.frame",
    row.names = c(NA,-20L)
  )

我正在使用 R,我正在尝试对这些数据进行子集化,并根据以下条件将列 time2 替换为新列:

  1. 将每个idtime1 的值求和,直到它大于或等于该idtime2 的对应值。

  2. 用每个id 的相应time2 值替换time1 中求和终止的单元格。

  3. time2 列将替换为标记为status 的新列,该列由01 组成。也就是说,statustime1 的未替换值和0 的所有替换值time1 采用1

总之,我希望看到这样的结果:

df <-
  structure(
    list(
      id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L, 4L),
      time1 = c(12L, 5L, 3L, 23, 22L, 17L, 5L, 25L, 5L, 15L, 24L),
      status=c(1L,1L,1L,0L,0L,1L,1L,0L,1L,1L,0L)
    ),
    .Names = c("id", "time1","status"),
    class = "data.frame",
    row.names = c(NA,-11L)
  )

非常感谢您对此提供的任何帮助。

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以做到以下几点:

    library(tidyverse);
    df %>%
        group_by(id) %>%
        mutate(
            status = as.numeric(cumsum(time1) < time2),
            time1 = ifelse(status == 1, time1, time2)) %>%
        group_by(id, status) %>%
        mutate(n = 1:n()) %>%
        ungroup() %>%
        filter(status == 1 | (status == 0 & n == 1)) %>%
        select(-n, -time2)
    ## A tibble: 11 x 3
    #      id time1 status
    #   <int> <int>  <dbl>
    # 1     1    12     1.
    # 2     1     5     1.
    # 3     1     3     1.
    # 4     1    23     0.
    # 5     2    22     0.
    # 6     3    17     1.
    # 7     3     5     1.
    # 8     3    25     0.
    # 9     4     5     1.
    #10     4    15     1.
    #11     4    24     0.
    

    说明:我们按id对行进行分组,然后计算time1条目的累积总和,并将cumsum(time1) &lt; time2所在的行标记为1,否则标记为0;如果status == 1,我们将time1 条目替换为time2 条目。最后我们需要删除多余的status = 0 行;为此,我们按idstatus 重新组合,对行进行连续编号,并为status = 0id 保留一行。

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 2019-07-08
      • 1970-01-01
      • 2021-09-08
      • 2016-04-07
      • 2022-08-11
      • 1970-01-01
      • 2021-09-29
      • 2021-10-13
      相关资源
      最近更新 更多