尝试使用dplyr找到平均时间并按V1分组
y <- x %>%
group_by(V1) %>%
mutate(V2=mean(chron(times = V2))) %>%
as.data.frame(y)
给出错误
Error in mutate_(.data, .dots = compat_as_lazy_dots(...)) :
argument ".data" is missing, with no default
下面的示例数据。任何帮助将不胜感激。
V1 V2
a 8:12:29
a 8:19:39
a 8:25:32
b 8:30:19
b 8:30:44
b 8:31:18
c 8:32:52
c 8:32:58
d 9:03:50
d 9:06:02
d 9:06:57
d 9:08:27
e 9:59:45
答案 0 :(得分:1)
尝试以下方法:
library(tidyverse)
df %>%
type_convert() %>%
group_by(V1) %>%
mutate(mean_time = mean(V2)) %>%
ungroup()
# A tibble: 13 x 3
V1 V2 mean_time
<chr> <time> <time>
1 a 08:12:29 08:19:13.333333
2 a 08:19:39 08:19:13.333333
3 a 08:25:32 08:19:13.333333
4 b 08:30:19 08:30:47.000000
5 b 08:30:44 08:30:47.000000
6 b 08:31:18 08:30:47.000000
7 c 08:32:52 08:32:55.000000
8 c 08:32:58 08:32:55.000000
9 d 09:03:50 09:06:19.000000
10 d 09:06:02 09:06:19.000000
11 d 09:06:57 09:06:19.000000
12 d 09:08:27 09:06:19.000000
13 e 09:59:45 09:59:45.000000
如果您愿意,还可以使用lubridate
来更改格式。例如:
df$mean_time <- lubridate::hms(df$mean_time)
# A tibble: 13 x 3
V1 V2 mean_time
<chr> <time> <S4: Period>
1 a 08:12:29 8H 19M 13.333333S
2 a 08:19:39 8H 19M 13.333333S
3 a 08:25:32 8H 19M 13.333333S
4 b 08:30:19 8H 30M 47S
5 b 08:30:44 8H 30M 47S
6 b 08:31:18 8H 30M 47S
7 c 08:32:52 8H 32M 55S
8 c 08:32:58 8H 32M 55S
9 d 09:03:50 9H 6M 19S
10 d 09:06:02 9H 6M 19S
11 d 09:06:57 9H 6M 19S
12 d 09:08:27 9H 6M 19S
13 e 09:59:45 9H 59M 45S