我正在尝试使用
quarter()
包的 lubridate
功能创建一个表格,计算每个财政季度参与的人数。
出于故障排除目的,这是可重现的数据集(简化):
structure(list(`ID Number` = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11
), `Date Record Created` = structure(c(1624492800,
1624492800, 1624579200, 1624924800, 1625788800, 1627948800, 1628208000,
1629244800, 1629849600, 1629849600), tzone = "UTC", class = c("POSIXct",
"POSIXt"))), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))
根据其文档(https://lubridate.tidyverse.org/reference/quarter.html),
quarter()
函数可以“获取 POSIXct、POSIXlt、Date、chron、yearmon 类的日期时间对象, yearqtr、zoo、zooreg、timeDate、xts、its、ti、jul、timeSeries、fts 或任何其他可以使用 as.POSIXlt 转换的内容”。我选择的日期列的格式为 POSIXct
,字符检查产生以下输出:
str(peopledata$`Date Record Created`)
POSIXct[1:339], format: "2021-06-24" "2021-06-24" "2021-06-25" "2021-06-29" "2021-07-09" "2021-08-03" "2021-08-06" "2021-08-18" "2021-08-25" "2021-08-25" ...
我运行此函数是为了将日期分组到其财政季度中:
library(tidyverse)
library(lubridate)
people<-peopledata%>%
select(`ID Number`,`Date Record Created`)%>%
quarter(`Date Record Created`,with_year=TRUE)
当我运行该函数时,出现以下错误:
Error in as.POSIXlt.default(x, tz = tz(x)) :
do not know how to convert 'x' to class “POSIXlt”
> traceback()
8: stop(gettextf("do not know how to convert '%s' to class %s",
deparse1(substitute(x)), dQuote("POSIXlt")), domain = NA)
7: as.POSIXlt.default(x, tz = tz(x))
6: as.POSIXlt(x, tz = tz(x))
5: month(as.POSIXlt(x, tz = tz(x))$mon + 1, label, abbr, locale = locale)
4: month.default(x)
3: month(x)
2: quarter(., `Date Record Created`, with_year = TRUE)
1: peopledata %>% select(`ID Number`, `Date Record Created`) %>%
quarter(`Date Record Created`, with_year = TRUE)
然后我尝试返回源数据并在列上运行
as.Date()
转换,但它引发了不同的错误:
输入:
peopledata<-read_excel("../People Activity.xlsx", sheet='People', col_names = T, col_types = NULL, na="", skip = 0)%>%
filter_all(any_vars(!is.na(.)))%>%
as.Date(`Date Record Created`, format = '%Y-%m-%d')
错误和回溯:
Error in as.Date.default(., `Date Record Created`, format = "%Y-%m-%d") :
do not know how to convert '.' to class “Date”
> traceback()
4: stop(gettextf("do not know how to convert '%s' to class %s",
deparse1(substitute(x)), dQuote("Date")), domain = NA)
3: as.Date.default(., `Date Record Created`, format = "%Y-%m-%d")
2: as.Date(., `Date Record Created`, format = "%Y-%m-%d")
1: read_excel("../People Activity.xlsx",
sheet = "People", col_names = T, col_types = NULL,
na = "", skip = 0) %>% filter_all(any_vars(!is.na(.))) %>%
as.Date(`Date Record Created`, format = "%Y-%m-%d")
>
我哪里出错了?
如果您使用
pull
而不是 select
,则有效:
peopledata %>%
pull(`Date Record Created`) %>%
quarter(., type="year.quarter")
#> [1] 2021.2 2021.2 2021.2 2021.2 2021.3 2021.3 2021.3 2021.3 2021.3 2021.3