[英]How do you calculate means for time differences for groups in R?
I am trying to calculate the mean time for national sailing teams in a competition.我正在尝试计算国家帆船队在比赛中的平均时间。
I want to group the teams together by country to calculate the mean sailing time for USA and Japan.我想按国家/地区将团队分组,以计算美国和日本的平均航行时间。
Here's my code, which uses the dplyr function's group_by.这是我的代码,它使用了 dplyr 函数的 group_by。
Here's the data这是数据
test <- data.frame("RACER" = c("USA",
"JAPAN",
"JAPAN"),
"TRIAL1" = c("2021-01-01",
"2021-01-05",
"2021-01-10"),
"TRIAL2" = c("2021-02-01",
"2021-02-04",
"2021-02-25"),
stringsAsFactors = FALSE)
test$TRIAL1 <- as.Date(test$TRIAL1)
test$TRIAL2 <- as.Date(test$TRIAL2)
test$delay <- difftime(test$TRIAL2, test$TRIAL1)
test$delay <- as.double(test$delay)
Here's my code:这是我的代码:
t <- test %>% group_by(RACER) %>%
summarize(mn = mean(test$delay, na.rm=T))
I get a mean of 35.7 days for both Japan and the US, which is wrong.日本和美国的平均时间都是 35.7 天,这是错误的。
Any suggestions?有什么建议么?
I hope this is what you are looking for:我希望这是您正在寻找的:
test %>%
group_by(RACER) %>%
summarise(mn = mean(delay, na.rm = TRUE))
# A tibble: 2 x 2
RACER mn
<chr> <dbl>
1 JAPAN 38
2 USA 31
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.