我正在尝试转换我的tibble格式中的日期,该格式目前是、3、季度、(字符)格式,但我试图将其转换为一年月(日期)格式。预期产出应为2001-03-01年。
在tibble中有不止一个日期,所以我不能仅仅重新格式化2001年3月的一个季度。
如果我的措辞令人困惑,我很抱歉,我正在尽我最大的努力用语言表达我的问题。有人能帮我吗?
发布于 2021-05-02 21:46:05
试试这个:
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列中分隔日期列,并使用as.Date指定格式为整年、全月名称和日期,由破折号。
发布于 2021-05-02 23:36:13
使用注释末尾定义的输入和动物园中的as.yearmon,我们可以将日期转换为一年对象,然后as.Date将使用动物园中的as.Date.yearmon,将其转换为date对象。frac=1的意思是使用月份的最后一天。下面的代码给出日期类输出,这很可能是您想要的,但是如果您想要字符类输出,则将格式应用于下面代码的输出,即格式(.)在哪里..。是下面的代码。
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")https://stackoverflow.com/questions/67361277
复制相似问题