簡體   English   中英

如何將季度(chr)格式的日期轉換為年月(日期)格式?

[英]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列拆分為三列以分離出三個單詞
  • 創建一個新列“dt”,其中包含年、月和“01”(將是日),用破折號分隔
  • 使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM