尝试将多个字符变量转换为日期时间。简化示例:
#create df/tibble with two "datetime" columns still as character
df=tibble(date1=c("2013-11-26 00:10:12.536","2013-11-26 23:04:32.512","2014-02-19 23:34:44.459"),
date2=c("2013-11-26 07:06:40.720","2013-11-27 07:09:50.552","2014-02-20 08:00:03.975"))
datetimeFormat="%Y-%m-%d %H:%M:%OS"
#OK: converting a single var using $
df_temp=df
df_temp$date1=as_datetime(df_temp$date1,format = datetimeFormat)
#not OK: converting a single var using indexing (presumably because df_temp[,"date1"] is still a tibble)
df_temp=df
df_temp[,"date1"]=as_datetime(df_temp[,"date1"],format = datetimeFormat)
#also not OK: converting multiple variables in one go
datetimeVars=c("date1","date2")
df_temp=df
df_temp[,datetimeVars]=as_datetime(df_temp[,datetimeVars],format = datetimeFormat)
如何一次将多个字符列转换为日期时间,特别是使用包含变量名的变量(如上面的datetimeVars(?
一些上下文:
- 我的源csv文件不是统一的,并且包含一个变量——通常是大量的日期时间(如上例所示的自定义格式(。我可以根据变量的名称来确定哪些变量应该成为datetime
- readcsv不一致地将相关变量识别为datetime
- read_csv似乎不允许同时为多个变量设置变量类型,因此不能执行以下操作:
df=read_csv("myFile.csv",col_types=cols(datetimeVars=col_datetime(format=datetimeFormat)))
我也不能为每个相关变量(如cols(date1=col_datetime(),date2=col_datettime, date3=...)
(指定/硬编码变量类型,因为日期时间变量的数量事先未知
因此,目前在导入(read_csv(和转换(as_datetime(两个级别都停滞不前。欢迎提出建议。
处理转换部分,因为导入高度依赖于文件和包含的格式。
使用as.POSIXct
转换为date
类(请记住,date
类始终以打印的格式显示,但在类对象中保留更多信息-请参阅下面的阅读(。
library(dplyr)
datetimeVars <- c("date1", "date2")
df_date <- df %>%
summarise(across(all_of(datetimeVars), as.POSIXct))
df_date
# A tibble: 3 × 2
date1 date2
<dttm> <dttm>
1 2013-11-26 00:10:12 2013-11-26 07:06:40
2 2013-11-26 23:04:32 2013-11-27 07:09:50
3 2014-02-19 23:34:44 2014-02-20 08:00:03
或者列名与起始模式(starts_with()
(匹配
datetimeVars <- c("date")
df_date <- df %>%
summarise(across(starts_with(datetimeVars), as.POSIXct))
df_date
# A tibble: 3 × 2
date1 date2
<dttm> <dttm>
1 2013-11-26 00:10:12 2013-11-26 07:06:40
2 2013-11-26 23:04:32 2013-11-27 07:09:50
3 2014-02-19 23:34:44 2014-02-20 08:00:03
使用strftime
从date
类中阅读您想要的格式
df_date %>%
summarise(across(starts_with("date"), strftime, format="%Y-%m-%d %H:%M:%OS3"))
# A tibble: 3 × 2
date1 date2
<chr> <chr>
1 2013-11-26 00:10:12.536 2013-11-26 07:06:40.720
2 2013-11-26 23:04:32.512 2013-11-27 07:09:50.552
3 2014-02-19 23:34:44.459 2014-02-20 08:00:03.974