【问题标题】:Data manipulation in R with data over timeR 中随时间变化的数据操作
【发布时间】:2020-01-09 17:09:03
【问题描述】:

基于下面的 R data.frame,我正在寻找一种优雅的解决方案来计算不同时间组之间转换的人数。

dat <- data.frame(people = c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4),
                  time = c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5),
                  group = c(5,4,4,3,2,4,4,3,2,1,5,5,4,4,4,3,3,2,2,1))

我想要一个通用的解决方案,因为我的问题规模要大得多。我正在考虑使用 mutate 的东西可以实现这一点,但我不知道从哪里开始

我正在寻找的输出开头的示例如下:

dat_result <- data.frame(time_start = c(1,1,1,1,1),
                         time_end = c(2,2,2,2,2),
                         group_start = c(1,1,1,1,1),
                         group_end = c(1,2,3,4,5),
                         count = "")

这将在所有时间转换和所有组转换中重复。时间当然是线性的,所以 1 只能到 2,2 到 3 等等。但是,任何组都可以转换到任何其他组,包括在不同时间之间留在同一组。

【问题讨论】:

    标签: r dataframe data-manipulation dplyr


    【解决方案1】:

    我正在使用包data.table,因为它可以轻松地按组工作。使用 dplyr 也可以执行相同的步骤,但我不熟悉它。

    library(data.table)
    
    # Convert to data.table:
    setDT(dat)
    
    # Make sure your data is ordered by people and time:
    setorder(dat, people, time)
    
    # Create a new column with the next group
    dat[, next.group := shift(group, -1), by = people]
    
    # Remove rows where there's no change:
    # (since this will remove data, you may want to atributte to a new object)
    new <- dat[group != next.group]
    
    # Add end.time:
    new[, end.time := shift(time, -1, max(dat$time)), by = people]
    
    # Count the ocurrences (and order the result):
    > new[, .N, by = .(time, end.time, group, next.group)][order(time, end.time, group)]
       time end.time group next.group N
    1:    1        3     5          4 1
    2:    2        3     4          3 1
    3:    2        4     3          2 1
    4:    2        5     5          4 1
    5:    3        4     3          2 1
    6:    3        4     4          3 1
    7:    4        5     2          1 2
    8:    4        5     3          2 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2011-11-26
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2015-07-13
      相关资源
      最近更新 更多