在独立的mm:ss值开始时添加00:,但在r中的同一列中不存在hh:mm:ss值



我在一列中有以下时间,并希望将独立的mm:ss值更改为00:mm:ss。最后的输出必须是数字。

我不知道从哪里开始。我认为gsub()可能是一个合适的解决方案,但我不确定语法只添加到独立的mm:ss值。

This is what I see in excel
Name    Section Role    Last Activity   Total Activity
A   biology Student Feb 8 at 1:08pm 18:16
B   biology Student Feb 8 at 1:37pm 3:22:10
C   biology Student Feb 8 at 10:37pm    9:51
D   biology Student Feb 8 at 11:50am    5:32:31
E   biology Student Feb 9 at 12:08pm    7:17:49
F   biology Student Feb 10 at 1:33am    12:25:41
This is what I see when I import this into R
structure(list(Name = c("A", "B", "C", "D", "E", "F"), Section = c("biology", 
"biology", "biology", "biology", "biology", "biology"), Role = c("Student", 
"Student", "Student", "Student", "Student", "Student"), `Last Activity` = c("Feb 8 at 1:08pm", 
"Feb 8 at 1:37pm", "Feb 8 at 10:37pm", "Feb 8 at 11:50am", "Feb 9 at 12:08pm", 
"Feb 10 at 1:33am"), `Total Activity` = structure(c(-2209009440, 
-2209063070, -2209039740, -2209055249, -2209048931, -2209030459
), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

以下是对您的问题的初步解决方案。请注意,这些值不是数字,因为没有数字25:12等。如果你想对它们进行计算,你可以将它们转换为日期,例如posix类。

ex <- c("20:28", 
"18:53", 
"25:01:00", 
"17:55", 
"27:04:00", 
"24:43:00") 

ex[stringr::str_count(ex, ":") == 1] <- gsub("^", 
"00:",  
ex[stringr::str_count(ex, ":") == 1])

> ex
[1] "00:20:28" "00:18:53" "25:01:00"
[4] "00:17:55" "27:04:00" "24:43:00"

可以计算数据中的字符数,如果小于8,则将'00:'加在前面。

df <- data.frame(time = c("20:28", "18:53", "25:01:00", "17:55", "27:04:00", "24:43:00"))
df <- transform(df, time = ifelse(nchar(time) < 8, paste0('00:', time), time))
df
#      time
#1 00:20:28
#2 00:18:53
#3 25:01:00
#4 00:17:55
#5 27:04:00
#6 24:43:00

对于更新后的数据集,我们可以将列Last Activity转换为日期-时间,并使用format

library(lubridate)
library(dplyr)
df <- df %>%
mutate(`Last Activity` = format(ymd_hm(paste('2020', `Last Activity`)), '%T'), 
`Total Activity` = format(`Total Activity`, '%T'))
df
#  Name  Section Role    `Last Activity`  `Total Activity`
#  <chr> <chr>   <chr>   <chr>            <chr>           
#1 A     biology Student Feb 8 at 1:08pm  18:16:00        
#2 B     biology Student Feb 8 at 1:37pm  03:22:10        
#3 C     biology Student Feb 8 at 10:37pm 09:51:00        
#4 D     biology Student Feb 8 at 11:50am 05:32:31        
#5 E     biology Student Feb 9 at 12:08pm 07:17:49        
#6 F     biology Student Feb 10 at 1:33am 12:25:41    

最新更新