R 将时间转换为十进制小时或十进制分钟
我有行为观察,观察的开始时间和每个行为的时间。开始时间的格式为hh:mm,观察开始后的行为时间为mm:ss 我想将开始时间转换为从午夜开始的小时数(例如,12:30为12.5),将行为时间转换为观察开始后的分钟数(例如,1:30为1.5) 到目前为止,我已经尝试了以下方法:R 将时间转换为十进制小时或十进制分钟,r,datetime,lubridate,R,Datetime,Lubridate,我有行为观察,观察的开始时间和每个行为的时间。开始时间的格式为hh:mm,观察开始后的行为时间为mm:ss 我想将开始时间转换为从午夜开始的小时数(例如,12:30为12.5),将行为时间转换为观察开始后的分钟数(例如,1:30为1.5) 到目前为止,我已经尝试了以下方法: #1 - results in NA values library(lubridate) df <- mutate(df, startTimeH = strtoi(as.difftime(as
#1 - results in NA values
library(lubridate)
df <- mutate(df,
startTimeH = strtoi(as.difftime(as.character(startTime), format = "%H:%M:%S", units = "hours")),
behavTimeM = strtoi(as.difftime(as.character(behavTime), format = "%M:%S", units = "mins")))
#2 - unclear what happens with this approach, matrix-like
df <- mutate(df,
startTimeH = hms(startTime),
behavTimeM = ms(behavTime))
您可以使用一点dplyr和tidyr代码来实现这一点:
library(dplyr)
library(tidyr)
# I read your data to two different objects
df <- tibble(startTime, behavTime)
df_new <- df %>%
# your data is a factor (I assume from wrong options during reading it in)
mutate_if(is.factor, as.character) %>%
# We seperate the column into hours, minutes and seconds
separate(startTime, into = c("startTime_hh", "startTime_mm"), ":") %>%
separate(behavTime, into = c("behavTime_mm", "behavTime_ss"), ":") %>%
# We convert the time into fractions of an hour
mutate(startTime_hh = as.numeric(startTime_hh),
startTime_mm = as.numeric(startTime_mm) / 60,
behavTime_mm = as.numeric(behavTime_mm) / 60,
behavTime_ss = as.numeric(behavTime_ss) / 3600) %>%
# lastly we reassemble the times
mutate(startTime = startTime_hh + startTime_mm,
behavTime = behavTime_mm + behavTime_ss)
库(dplyr)
图书馆(tidyr)
#我将您的数据读取到两个不同的对象
df%
#我们把这个列分成小时、分钟和秒
分离(起始时间,分为=c(“起始时间”、“起始时间”、“:”)%>%
分离(behavTime,into=c(“behavTime_-mm”,“behavTime_-ss”),“:”%>%
#我们把时间换算成一小时的分数
变异(startTime\u hh=as.numeric(startTime\u hh),
startTime_mm=作为数字(startTime_mm)/60,
behavTime_-mm=作为数值(behavTime_-mm)/60,
behavTime\u ss=as.numeric(behavTime\u ss)/3600)%
#最后,我们重新组合时代
突变(startTime=startTime\u hh+startTime\u mm,
behavTime=behavTime\u mm+behavTime\u ss)
谢谢@JBGruber!这对我的数据集非常有效。也非常感谢您对mutate_if函数的详细评论和介绍。
library(dplyr)
library(tidyr)
# I read your data to two different objects
df <- tibble(startTime, behavTime)
df_new <- df %>%
# your data is a factor (I assume from wrong options during reading it in)
mutate_if(is.factor, as.character) %>%
# We seperate the column into hours, minutes and seconds
separate(startTime, into = c("startTime_hh", "startTime_mm"), ":") %>%
separate(behavTime, into = c("behavTime_mm", "behavTime_ss"), ":") %>%
# We convert the time into fractions of an hour
mutate(startTime_hh = as.numeric(startTime_hh),
startTime_mm = as.numeric(startTime_mm) / 60,
behavTime_mm = as.numeric(behavTime_mm) / 60,
behavTime_ss = as.numeric(behavTime_ss) / 3600) %>%
# lastly we reassemble the times
mutate(startTime = startTime_hh + startTime_mm,
behavTime = behavTime_mm + behavTime_ss)