![](/img/trans.png)
[英]Convert numeric date format (YYYYMMDD; 20150101) into Year-Month
[英]How do I convert dates in Quarter-Year (chr) format to Year-Month (date) format?
我正在嘗試將我的 tibble 中的日期轉換為2001 年 3 月季度(字符)格式,但我正在嘗試將其轉換為年月(日期)格式。 預期的 output 應該是 2001-03-01。
標題中有不止一個日期,所以我不能只重新格式化那個 2001 年 3 月季度。
如果我的措辭令人困惑,我深表歉意,我正在盡力將我的問題用語言表達出來。 有人可以幫我嗎?
嘗試這個:
library(tidyr)
library(dplyr)
df %>%
separate(col = quarter, into = c('Month', 'drop', 'Year'), sep = ' ') %>%
mutate(dt = paste(Year, Month, '01', sep = '-')) %>%
mutate(Date = as.Date(dt, format = '%Y-%B-%d')) %>%
select(-drop, -dt, -Month, -Year)
解釋:
separate
列拆分為三列以分離出三個單詞as.Date
從 dt 列創建 Date 列,並將格式指定為全年、全月名稱和用破折號分隔的日期 使用最后注釋中定義的輸入和來自 zoo 的as.yearmon
,我們可以將日期轉換為 yearmon object,然后as.Date
將使用來自 zoo 的 as.Date.yearmon 將其轉換為 Date object。 frac=1 表示使用該月的最后一天。 The code below gives Date class output which is likely what you want but if you want character class output apply format to the output of the code below, ie format(...) where... is the code below.
library(zoo)
as.Date(as.yearmon(x, "%B quarter %Y"), frac = 1)
## [1] "2001-03-31" "2001-06-30" "2001-09-30" "2001-12-31"
x <- c("March quarter 2001", "June quarter 2001", "September quarter 2001",
"December quarter 2001")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.