格式日期为年/季 [英] Format date as Year/Quarter

查看:124
本文介绍了格式日期为年/季的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

Data <- data.frame(
  date = c("2001-01-01", "2001-02-01", "2001-03-01", "2001-04-01", "2001-05-01", "2001-06-01"),
  qtr = c("NA", "NA","NA","NA","NA","NA")
)

我想用Year / Quater填充Data $ qtr - fe 01/01(我需要这个格式!)。

I want to fill Data$qtr with Year/Quater - f.e. 01/01 (I need this format!).

我写了一个函数:

fun <- function(x) { 
  if(x == "2001-01-01" | x == "2001-02-01" | x == "2001-03-01") y <- "01/01"
  if(x == "2001-04-01" | x == "2001-05-01" | x == "2001-06-01") y <- "01/02"
  return(y)
}
n$qtr <- sapply(n$date, fun)

但它不起作用我总是收到错误信息:

But it does not work. I always get the error message:

Error in FUN(X[[1L]], ...) : Object 'y' not found

为什么?

推荐答案

您需要具体说明 Vectorize 您的功能:

You need to explicilty Vectorize your function:

fun_v <- Vectorize(fun, "x")
fun_v(Data$date)
#[1] "01/01" "01/01" "01/01" "01/02" "01/02" "01/02"

然而,当谈到更多或更少的标准任务(如日期时间操作),总是有一个可用的解决方案:

However, when it comes to more or less standard tasks (such as datetime manipulations), there's always a solution already available:

library(zoo)
yq <- as.yearqtr(Data$date, format = "%Y-%m-%d")
yq
#[1] "2001 Q1" "2001 Q1" "2001 Q1" "2001 Q2" "2001 Q2" "2001 Q2"

要转换为特定格式,请使用

To convert to your specific format, use

format(yq, format = "%y/0%q")
#[1] "01/01" "01/01" "01/01" "01/02" "01/02" "01/02"

这篇关于格式日期为年/季的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆