Floor_date 不适用于 mutate 和 ifelse
我试图编写一个概括的聚合函数,其中用户指定聚合级别,或者可以在所有研究日期汇总数据。 floor_date
仅转换第一个日期。为什么?我该如何解决?
library(dplyr)
library(lubridate)
sTerm <- "year" # month, bimonth, quarter, season, halfyear and year, custom
sCustom <- "2023-2025"
dfDatasetOutput <- data.frame(
valDate=seq(as.Date("2023-01-01"), as.Date("2025-12-01"), by = "month"),
cat1=rnorm(36, 3500, 1000),
cat2=rnorm(36, 2.5, 5)
)
dfDatasetOutput %>%
mutate(valDate=ifelse(toupper(sTerm)=="CUSTOM",
sCustom,
as.character(floor_date(valDate, sTerm))))
# this works just fine
dfDatasetOutput %>%
mutate(valDate=as.character(floor_date(valDate, sTerm)))
I am trying to write a generalize aggregation function where the user specifies the aggregation level or they can aggregate the data over all study dates. The floor_date
only converts the first date. why? How can I fix this?
library(dplyr)
library(lubridate)
sTerm <- "year" # month, bimonth, quarter, season, halfyear and year, custom
sCustom <- "2023-2025"
dfDatasetOutput <- data.frame(
valDate=seq(as.Date("2023-01-01"), as.Date("2025-12-01"), by = "month"),
cat1=rnorm(36, 3500, 1000),
cat2=rnorm(36, 2.5, 5)
)
dfDatasetOutput %>%
mutate(valDate=ifelse(toupper(sTerm)=="CUSTOM",
sCustom,
as.character(floor_date(valDate, sTerm))))
# this works just fine
dfDatasetOutput %>%
mutate(valDate=as.character(floor_date(valDate, sTerm)))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该问题并非源于
floor_date
,而是源于您使用ifelse
。根据其手册:您的测试是
toupper(sTerm)=="CUSTOM"
这是单个逻辑元素 TRUE 或 FALSE(或 NA)。因此 ifelse 的输出将是单个元素。如果测试结果为 false,它将从as.character(floor_date(valDate, sTerm))
中获取此元素。它只需要一个,因此将采用第一个。然后mutate
将此单个值回收到列的长度。如果您希望输出的长度与
valDate
相同,解决方法是重复测试,以便获得所需长度的向量作为测试:为了避免意外使用
ifelse
,请考虑使用if_else
它对对象长度进行检查。The problem does not stem from
floor_date
but from your use ofifelse
. As per its manual:Your test is
toupper(sTerm)=="CUSTOM"
which is a single logical element TRUE or FALSE (or NA). So the output ofifelse
will be a single element. If the test is false, it will take this element fromas.character(floor_date(valDate, sTerm))
. It only needs one, so will take the first one. Thenmutate
recycles this single value to the length of the column.If you want the output to be the same length as
valDate
, a workaround would be to repeat your test so you get a vector of the desired length as a test:To avoid such unintended use of
ifelse
, consider usingif_else
which runs checks on object lengths.