[英]How to convert all factor variables into numeric variables (in multiple data frames at once)?
[英]How to convert multiple character variables to datetime at once?
尝试将多个字符变量转换为日期时间。 简化示例:
#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 )?
一些背景:
df=read_csv("myFile.csv",col_types=cols(datetimeVars=col_datetime(format=datetimeFormat)))
我也可以't 为每个相关变量指定/硬编码变量类型,如cols(date1=col_datetime(),date2=col_datettime, date3=...)
因为日期时间变量的数量无法提前知道所以目前停留在导入(read_csv)和转换(as_datetime)两个级别。 欢迎提出建议。
由于导入高度依赖于文件和包含的格式,因此处理转换部分。
使用as.POSIXct
转换为date
class(请记住, date
class 始终以打印格式显示,但在 class object 中保留更多信息 - 请参阅下文阅读)。
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
class读取您想要的格式
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.