【问题标题】:Finding the closest values above and below a certain date by group按组查找高于和低于某个日期的最接近的值
【发布时间】:2021-03-30 07:42:30
【问题描述】:

我有一个纵向测量数据框,我希望找到在某个日期前后进行的最接近的测量。我的日期列被编码为自研究开始以来的天数。

对于每个参与者,我想找到最接近研究 100 天以下值的测量值和最接近研究 100 天以上值的测量值。如果参与者有 100 天的测量值,那么我希望返回该值。

我的数据框如下所示:

df <- data_frame(id = c(1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3), 
measures = c(10, 11, 11.4, 11.7, 11.8, 4.1, 4.3, 4.7, 13.3, 13.2, 13.5, 13.9, 14, 14.1),
days = c(5, 45, 60, 94, 104, 21, 76, 115, 10, 26, 73, 100, 132, 154))

df
# id measures days
# 1     10       5
# 1     11      45
# 1     11.4    60
# 1     11.7    94
# 1     11.8   104
# 2      4.1    21
# 2      4.3    76
# 2      4.7   115
# 3     13.3    10
# 3     13.2    26
# 3     13.5    73
# 3     13.9   100
# 3     14     132
# 3     14.1   154

对于 ID 1,我希望它返回第 94 天和第 104 天以及测量值 11.7 和 11.8。对于 ID 2,我希望它返回第 76 天和第 115 天以及测量值 4.3 和 4.7。对于 ID 3,我希望它返回第 100 天两次并测量 13.9 两次。

这是我目前所拥有的:

library(dplyr)
df %>% group_by(id) %>% 
summarise(below = max(df$days[df$days <= 100]),
          above = min(df$days[df$days >= 100]),
          below_msrmt = df$measures[which(df$days == below)],
          above_msrmt = df$measures[which(df$days == above)])

但看起来代码没有读取 group_by 参数,因为它一直给我这个:

# id below above below_msrmt above_msrmt
# 1    100   100        13.9        13.9
# 2    100   100        13.9        13.9
# 3    100   100        13.9        13.9

谁能帮我解决这个问题?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    如果我们删除df$,它会起作用,因为df$daysdf$measures 会选择整个列,而不仅仅是每个组中那些列的值。因此,我们得到所有组的相同值,因为它是整个列的汇总值

    df %>% group_by(id) %>% 
        summarise(below = max(days[days <= 100]),
          above = min(days[days >= 100]),
          below_msrmt = measures[which(days == below)],
          above_msrmt = measures[which(days == above)])
    

    【讨论】:

    • 哦,哇,谢谢。我已经为此苦苦挣扎了很久。你知道为什么删除 df$ 可以解决问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多