如何在r中以hr:min格式获取列中的平均时间?
我有类似的数据如何在r中以hr:min格式获取列中的平均时间?,r,R,我有类似的数据 mode departure_time activity_purpose car 7:08 work car 8:45 work bike 6:34 school walk 5:45 work walk 6:20 school 如何计算每个活动目的的
mode departure_time activity_purpose
car 7:08 work
car 8:45 work
bike 6:34 school
walk 5:45 work
walk 6:20 school
如何计算每个活动目的的平均出发时间?以及如何绘制图表来显示发车时间分布?y应为计数,x应为起飞时间,格式为5:00、6:00、7:00等
谢谢你的帮助 这里有一种方法:
library(dplyr)
#Read in data
tib <- tibble::tribble(
~mode, ~departure_time, ~activity_purpose,
'car', '7:08', 'work',
'car', '8:45', 'work',
'bike', '6:34', 'school',
'walk', '5:45', 'work',
'walk', '6:20', 'school'
)
#Define function for mean time calculation
calc_mean_depart <- function(times){
#Extract hrs from time
hrs <- stringr::word(times, 1, sep = ':') %>%
#Convert to integer
as.integer() %>%
#Convert to minutes
magrittr::multiply_by(60)
#Extract minutes
min <- stringr::word(times, 2, sep = ':') %>%
#Convert to integer
as.integer()
#Get mean time in minutes
mean_time <- mean(hrs + min)
#Get the average number of hrs
mean_hrs <- floor(mean_time/60)
#Generate the output
paste0(
mean_hrs, ':', round(mean_time %% 60) ## Time mod 60 == minutes
)
}
#Calculate group-wise mean time
tib %>%
#Group on activity
dplyr::group_by(activity_purpose) %>%
#Get the mean
dplyr::summarise(
mean = calc_mean_depart(departure_time)
)
#Output:
# A tibble: 2 x 2
activity_purpose mean
<chr> <chr>
1 school 6:27
2 work 7:13
#Plot departure hr
tib %>%
dplyr::mutate(
hrs = stringr::word(departure_time, 1, sep = ':'),
hrs = as.integer(hrs)
) %>%
ggplot2::ggplot(ggplot2::aes(hrs))+
ggplot2::geom_histogram(binwidth = 1)
库(dplyr)
#读入数据
tib%
dplyr::突变(
hrs=stringr::word(出发时间,1,9月1日=':'),
小时=整数(小时)
) %>%
ggplot2::ggplot(ggplot2::aes(小时))+
ggplot2::geom_直方图(binwidth=1)
这就是您要寻找的:
lubridate
中的period\u to_seconds
功能获取周期元素group\u by
根据您的需要进行分组:这里您可以得到活动目的的平均出发时间(您可以根据需要进行调整)
计数
dttm
元素的步骤库(tidyverse)
图书馆(lubridate)
tib1%
分组依据(活动目的)%>%
变异(平均值=秒到秒周期(平均值(周期到秒周期)(hm(离开时间)щщ))%>%
计数(平均值)
tib2%
变异(平均日期时间=最低日期(系统时间(),“1天”)+平均值)
ggplot(数据=tib2,aes(x=平均日期时间,y=n))+
几何图形栏(stat=“identity”)
输出:
# Groups: activity_purpose [2]
activity_purpose average n
<chr> <Period> <int>
1 school 6H 27M 0S 2
2 work 7H 12M 40S 3
#小组:活动与目的[2]
活动目的平均数
1所学校6H 27M 0S 2
2工作时间7小时12米40秒3
谢谢你的帮助!还有两个问题。有什么方法可以在条形图中添加颜色,并在边上添加注释,以说明哪种颜色表示哪种用途?
# Groups: activity_purpose [2]
activity_purpose average n
<chr> <Period> <int>
1 school 6H 27M 0S 2
2 work 7H 12M 40S 3