【问题标题】:How to mutate new columns in R based on earliest and latest dates for other variables如何根据其他变量的最早和最晚日期来改变 R 中的新列
【发布时间】:2022-01-21 05:23:12
【问题描述】:

在每个患者进行多次测试并在每个测试日期得分的数据集中,我必须确定最早和最新的测试日期,然后减去这些日期的分数差。我想我已经通过 dplyr 确定了第一个和最后一个日期,并为这些创建了新列:

SplitDates <- SortedDates %>% 
  group_by(PatientID) %>% 
  mutate(EarliestTestDate = min(AdministrationDate), 
         LatestTestDate = max(AdministrationDate)) %>% 
  arrange(desc(PatientID))

分数栏是TotalScore

现在如何从这 2 个日期(针对每个患者)中提取分数以创建最早和最新分数的新列?无法使用 case_when 或 if_else 找出一个变异来根据特定日期的记录创建分数。

【问题讨论】:

  • 您可以使用AdministrationDate == EarliestTestDate | AdministrationDate == LatestTestDateAdministrationDate %in% range(AdministrationDate) 之类的条件进行过滤
  • 也可能使用 mutate 创建一个“最早 - 最新”列,例如SplitDates &lt;- SortedDates %&gt;% group_by(PatientID) %&gt;% mutate(EarliestTestDate = min(AdministrationDate), LatestTestDate = max(AdministrationDate), earliest_minus_latest = EarliestTestDate - LatestTestDate) %&gt;% arrange(desc(PatientID))
  • @jared_mamrot 我认为他们试图获得一些分数的差异,而不是日期本身。很难说没有reproducible example
  • 这些答案涵盖了如何获得最早/最晚考试日期的第一部分。我的问题的第二部分是:我有一个数字 TotalScore 列。我想通过某种方式从每个患者的 EarliestTestDate 和 LatestTestDate 的病例中获取 TotalScore,为 EarliestTestScore 和 LatestTestScore 创建新列。
  • 这就是为什么数据样本会有所帮助的原因,尽管我很确定应该已经有帖子涵盖了您

标签: r dplyr


【解决方案1】:

您是否尝试过使用一个组合动词,例如 left_join?

SplitDates <- SortedDates %>% 
    group_by(PatientID) %>% 
    mutate(EarliestTestDate = min(AdministrationDate), 
        LatestTestDate = max(AdministrationDate)) %>% 
    ungroup() %>%
    left_join(SortedDates,
        by = c(“PatientID” = “PatientID”, “AdministrationDate” = “EarliestTestDate”)) %>% # picking the score of EarliestTestDate
    left_join(SortedDates,
        by = c(“PatientID” = “PatientID”, “AdministrationDate” = “LatestTestDate”)) %>% # picking the score of EarliestTestDate
    arrange(desc(PatientID)) # now you can make the mutante task that you need.

我建议你看看dplyr cheatsheet

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-08
    • 2021-09-29
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2011-05-22
    • 2021-03-13
    • 2010-10-21
    相关资源
    最近更新 更多