【问题标题】:Finding the mean of a group, based on the most recent date of each group根据每个组的最近日期查找组的平均值
【发布时间】:2021-04-23 00:28:56
【问题描述】:

抱歉标题不清楚。 我的问题很简单,但很难说清楚。 如果我有样本数据集:

Person Date (m/d/y) Weight
Person1 01/15/21 93
Person2 01/16/21 87
Person3 01/14/21 73
Person1 01/17/21 95
Person2 01/15/21 85
Person3 01/18/21 73.5

在 R 中,我如何找到 Person1、2、3 权重的平均值。请记住,我只有他们最近的体重很重要。

因此,正确答案应该是:

  • Person1 (01/17/21) 体重 = 95;
  • Person2 (01/16/21) 体重 = 87;
  • Person3 (01/18/21) 体重 = 73.5;

平均值 = 85.2

【问题讨论】:

    标签: r filter dplyr shiny shinyapps


    【解决方案1】:

    一种选择是在最后一个日期按slice 进行分组,然后参加mean

    library(dplyr)
    df1 %>%
      group_by(Person) %>%
      slice(which.max(as.Date(`Date (m/d/y)`, '%m/%d/%y'))) %>%
      ungroup %>%
      summarise(Weight = mean(Weight, na.rm = TRUE))
    

    -输出

    # A tibble: 1 x 1
    #  Weight
    #   <dbl>
    #1   85.2
    

    数据

    df1 <- structure(list(Person = c("Person1", "Person2", "Person3", "Person1", 
    "Person2", "Person3"), `Date (m/d/y)` = c("01/15/21", "01/16/21", 
    "01/14/21", "01/17/21", "01/15/21", "01/18/21"), Weight = c(93, 
    87, 73, 95, 85, 73.5)), class = "data.frame", row.names = c(NA, 
    -6L))
    

    【讨论】:

    • 谢谢!这应该很好用!我可以问一个后续问题:这个小问题在我编码时发生了很多次,但是当我编写像你上面那样的代码时,R Shiny 找不到我引用的变量。为了解决这个问题,我必须写... ''' df1 %>% group_by(df1$Person) %>% slice(which.max(as.Date(df1$'Date (m/d/y)' , '%m/%d/%y'))) %>% ungroup %>% summarise (Weight = mean (Weight)) ''' 即使在上面的例子中,我也得到一个错误,其中 R 找不到权重。
    • @ZacharyMcClean 当然,继续
    • 警告:错误:summarise() 输入问题Weight。 x object 'Weight' not found ℹ Input Weight is mean(Weight)
    • @ZacharyMcClean 你不需要在里面使用df1$。另外,使用反引号代替单引号或双引号
    • 非常感谢,这非常有帮助.. 不仅针对这个特定问题,而且还扩大了我的 R 知识!
    【解决方案2】:

    这是一个data.table 选项

    setDT(df)[
      ,
      Weight[which.max(as.Date(`Date (m/d/y)`, format = "%m/%d/%y"))],
      Person
    ][
      ,
      mean(V1)
    ]
    

    给予

    [1] 85.16667
    

    数据

    > dput(df)
    structure(list(Person = c("Person1", "Person2", "Person3", "Person1",
    "Person2", "Person3"), `Date (m/d/y)` = c("01/15/21", "01/16/21",
    "01/14/21", "01/17/21", "01/15/21", "01/18/21"), Weight = c(93,
    87, 73, 95, 85, 73.5)), class = "data.frame", row.names = c(NA,
    -6L))
    

    【讨论】:

      猜你喜欢
      • 2014-03-31
      • 2013-06-01
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多