在R中转换非标准时间数据

发布于 2025-01-14 06:18:25 字数 460 浏览 0 评论 0原文

我有一个包含非标准时间数据的数据集 - Excel 文件具有各种不同格式的数字,如下所示。

输入图片此处描述

尝试将其转换为 R 中可用的内容 - 可能是 HH:MM AM/PM 所以我使用 mutate(H1B.format = format(strptime(H1B, "%I:%M %p"), "%H:%M"))。

我该怎么做 - 我尝试:separate(H1B, into = c('time', 'ampm​​'), sep = -2, conversion = TRUE) 将AM/PM放入单独的列中,但仍然需要计算了解如何根据需要添加冒号和零。

我对 R 也很陌生,所以任何帮助都会很棒!

I have a dataset with non-standard time data - the Excel file has numbers in a variety of different of different formats as shown below.

enter image description here

Trying to convert it to something usable in R - probably HH:MM AM/PM so I use mutate(H1B.format = format(strptime(H1B, "%I:%M %p"), "%H:%M")).

How would I do this - I tried: separate(H1B, into = c('time', 'ampm'), sep = -2, convert = TRUE) to put AM/PM into a separate column, but still need to figure out how to add colons and zeros as needed.

I'm also fairly new to R, so any help would be great!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲影 2025-01-21 06:18:26

您可以使用 lubridate::parse_date_time 来解析各种格式的时间。

library("lubridate")
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

times_to_parse <- c(
  "10:30PM", "9:30pm", "12am", "10pm", "6am", "5:30pm",
  "1015PM", "1030pm" 
)
time_formats <- c(
  "%I:%M %p", "%I %p"
)

lubridate::parse_date_time(
  times_to_parse, time_formats
)
#> [1] "0000-01-01 22:30:00 UTC" "0000-01-01 21:30:00 UTC"
#> [3] "0000-01-01 00:00:00 UTC" "0000-01-01 22:00:00 UTC"
#> [5] "0000-01-01 06:00:00 UTC" "0000-01-01 17:30:00 UTC"
#> [7] "0000-01-01 22:15:00 UTC" "0000-01-01 22:30:00 UTC"

reprex 软件包 (v2.0.1) 创建于 2022 年 3 月 15 日

You can use lubridate::parse_date_time to parse times in various formats.

library("lubridate")
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

times_to_parse <- c(
  "10:30PM", "9:30pm", "12am", "10pm", "6am", "5:30pm",
  "1015PM", "1030pm" 
)
time_formats <- c(
  "%I:%M %p", "%I %p"
)

lubridate::parse_date_time(
  times_to_parse, time_formats
)
#> [1] "0000-01-01 22:30:00 UTC" "0000-01-01 21:30:00 UTC"
#> [3] "0000-01-01 00:00:00 UTC" "0000-01-01 22:00:00 UTC"
#> [5] "0000-01-01 06:00:00 UTC" "0000-01-01 17:30:00 UTC"
#> [7] "0000-01-01 22:15:00 UTC" "0000-01-01 22:30:00 UTC"

Created on 2022-03-15 by the reprex package (v2.0.1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文