【问题标题】:How to create new row to ensure time series length is equal?如何创建新行以确保时间序列长度相等?
【发布时间】:2021-11-15 07:04:35
【问题描述】:

我正在尝试对治疗的有效性进行分类。每个 id 应包含 4 个时间范围。

Dataframe
id timeframe distance
1 1 1.1
1 2 1.1
1 3 1.2
1 4 1.1
2 1 1.1
2 2 1.1
2 4 1.1

问题是例如 id 2 timeframe #3 丢失。如何创建一个在缺失时间范围内添加的新行,其中包含所有存在此类问题的行的平均距离值?

我在运行时得到“并非所有时间都是相同的长度” - 使用“纵向 k 均值 (KML)”的纵向聚类

【问题讨论】:

    标签: r time-series


    【解决方案1】:

    我们可以使用complete 来创建缺失的组合,然后将NA 替换为mean

    library(dplyr)
    library(tidyr)
    df1 %>%
        mutate(rn = row_number()) %>%
        complete(id, timeframe) %>%
        mutate(distance = replace(distance, is.na(distance) & is.na(rn), 
              mean(distance, na.rm = TRUE)))
    

    如果mean 应该在每个“id”中计算,那么在mutate 之前执行group_by

    df1 %>%
        mutate(rn = row_number()) %>%
        complete(id, timeframe) %>%
        group_by(id) %>%
        mutate(distance = replace(distance, is.na(distance) & is.na(rn), 
              mean(distance, na.rm = TRUE))) %>%
        ungroup
    

    【讨论】:

    • 谢谢你的想法,但是如何在时间框架 #3 的行中添加呢?
    • @user9510596 您也可以添加该行,但这不会比complete 更手动,即完成将自动检查特定ID 是否缺少任何时间帧值
    • 我已经尝试了建议的方法。如果值中有 NA,它将用平均值替换该行。但是,在我的情况下,时间帧 #3 的整行都不存在于数据帧中,因此不会被视为 NA。
    • 是的,它终于可以工作了,正如你所提到的,它必须在变异之前先取消组合
    • @user9510596 您可能在其他步骤中使用了group_by,除非删除分组,否则它会保留并在您使用完整等时导致此问题
    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 2014-06-25
    相关资源
    最近更新 更多