抱歉,标题不清楚。我的问题很简单,但很难表达。如果我有样本数据集:
人 | 日期(月/日/年) | 重量 |
---|---|---|
人1 | 01/15/21 | 93 |
人2 | 01/16/21 | 87 |
人3 | 01/14/21 | 73 |
人1 | 01/17/21 | 95 |
人2 | 01/15/21 | 85 |
人3 | 01/18/21 | 73.5 |
在R中,我如何找到Person1,2,3权重的平均值。请记住,我只有他们最近的体重很重要。
因此,正确的答案应该是:
均值= 85.2
一种选择是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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句