![](/img/trans.png)
[英]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.