我得到了一个数据格式化文件,其中包含日期变量,这些变量被格式化为,例如,9/28/2017 16:00。我想把这些变量转换成连续的数值变量,比如在这个例子中的16 (其他如9/28/2017 : 17:00到17和9/30/2017 17:00到17 )。不管日期是什么,我只想要时间。我怎么能在R里这么做?
发布于 2022-05-08 04:27:05
提取数据的hour部分的一种方法是使用gsub
y <- as.POSIXct(c("9/28/2017 16:00", "9/28/2017 17:00"), format = "%m/%d/%Y %H:%M")
y
#[1] "2017-09-28 16:00:00 +07" "2017-09-28 17:00:00 +07"
#Here +7 is my timezone.
as.numeric(gsub("(.*?)\\s|\\:00*", "",y))
#[1] 16 17在“日期”具有字符类型的情况下,它也可以工作。
z <- "9/28/2017 16:00"
str(z)
#chr "9/28/2017 16:00"
as.numeric(gsub("(.*?)\\s|\\:00*", "",z))
#[1] 16发布于 2022-05-08 07:21:46
我发现使用lubridate包是最简单的。下面是一个tidyverse解决方案;基本思想是首先将date元素更改为日期-时间类型(我使用lubridate::mdy_hms完成此操作),然后使用lubridate::hour函数提取所需的时间。如果需要更多关于时间的信息,还可以使用hms::as_hms函数代替lubridate::hour函数。
library(tidyverse)
library(lubridate)
## creating an example tibble (dataframe) with two example dates
example_df <- tribble(~date, "9/28/2017 16:00", "9/28/2017 17:00")
## changing the date column to an date_time first, then extract hour from there in two different ways
## the first way uses lubridate::hour the second uses hms::as_hms
example_df %>%
mutate(date = mdy_hm(date)) %>%
mutate(hour = hour(date)) %>%
mutate(hour_minute = hms::as_hms(date))https://stackoverflow.com/questions/72157723
复制相似问题