在R中转换时间?

dw1jzc5e  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(105)

考虑从8:00(上午)到5:00(下午)的9个小时。将0设置为8:00(上午),将9设置为5:00(下午)。如果我们有一个向量x如下:

x = c(
0.03634568,0.47838162,0.80789109,0.99359959,1.02569362,1.55938143,
1.59509855,1.61406989,1.75217236,1.90665327,2.83467797,3.36134548,
3.93938312,4.06451236,4.38345992,4.47065016,4.70323660,4.81384233,
4.81655127,5.13904842,5.22296245,5.24547047,5.76230279,5.90503986,
6.59671006,7.03660356,7.35381102,8.79155176
)

如何将x转换为正常的时间格式,例如0.5表示8:30(上午),8.5表示4:30(下午)或16:30?
我已经尝试通过Convert time from numeric to time format in R作为

library(chron)
substr(times(x),1,5) #To strip off the seconds
# format(as.POSIXct((x) * 86400, origin = "1970-01-01", tz = "UTC"), "%H:%M")

但它并没有给出给予期望的结果。有什么需要帮忙的吗?

o7jaxewo

o7jaxewo1#

计算模和整数化中期结果。

h <- as.integer(x)
m <- as.integer((x %% 1)*60)
s <- as.integer((((x %% 1)*60) %% 1)*60)
sprintf('%02g:%02g:%02g', h, m, s)
#  [1] "00:02:10" "00:28:42" "00:48:28" "00:59:36" "01:01:32" "01:33:33" "01:35:42" "01:36:50" "01:45:07"
# [10] "01:54:23" "02:50:04" "03:21:40" "03:56:21" "04:03:52" "04:23:00" "04:28:14" "04:42:11" "04:48:49"
# [19] "04:48:59" "05:08:20" "05:13:22" "05:14:43" "05:45:44" "05:54:18" "06:35:48" "07:02:11" "07:21:13"
# [28] "08:47:29"
  • 数据:*
x <- c(0.03634568, 0.47838162, 0.80789109, 0.99359959, 1.02569362, 
1.55938143, 1.59509855, 1.61406989, 1.75217236, 1.90665327, 2.83467797, 
3.36134548, 3.93938312, 4.06451236, 4.38345992, 4.47065016, 4.7032366, 
4.81384233, 4.81655127, 5.13904842, 5.22296245, 5.24547047, 5.76230279, 
5.90503986, 6.59671006, 7.03660356, 7.35381102, 8.79155176)
efzxgjgh

efzxgjgh2#

根据具体的任务,hms可以非常方便:

x = c(
  0.03634568,0.47838162,0.80789109,0.99359959,1.02569362,1.55938143,
  1.59509855,1.61406989,1.75217236,1.90665327,2.83467797,3.36134548,
  3.93938312,4.06451236,4.38345992,4.47065016,4.70323660,4.81384233,
  4.81655127,5.13904842,5.22296245,5.24547047,5.76230279,5.90503986,
  6.59671006,7.03660356,7.35381102,8.79155176
)

library(hms)
tibble::tibble(
  hms_   = as_hms(hms(hours = 8) + x*60*60),
  round_ = as_hms(hms(hours = 8) + x*60*60) |> round_hms(secs = 1),
  trunc_ = as_hms(hms(hours = 8) + x*60*60) |> trunc_hms(secs = 1)
)
#> # A tibble: 28 × 3
#>    hms_            round_   trunc_  
#>    <time>          <time>   <time>  
#>  1 08:02:10.844448 08:02:11 08:02:10
#>  2 08:28:42.173832 08:28:42 08:28:42
#>  3 08:48:28.407924 08:48:28 08:48:28
#>  4 08:59:36.958524 08:59:37 08:59:36
#>  5 09:01:32.497032 09:01:32 09:01:32
#>  6 09:33:33.773148 09:33:34 09:33:33
#>  7 09:35:42.354780 09:35:42 09:35:42
#>  8 09:36:50.651604 09:36:51 09:36:50
#>  9 09:45:07.820496 09:45:08 09:45:07
#> 10 09:54:23.951772 09:54:24 09:54:23
#> # ℹ 18 more rows

创建于2023-10-04带有reprex v2.0.2

相关问题