首页 > 解决方案 > 将函数应用于R中的列表的问题

问题描述

我创建了一个将“YYYYQQ”转换为整数 YYYYMMDD 的函数。该函数适用于列表中的单个值,但不适用于整个列表。我不是无法理解警告信息。

GetProperDate <- function(x) {
     x <- as.character(x)
     q<-substr(x, 5, 6)
     y<-substr(x, 1,4) %>% as.numeric()
      if(q=="Q1"){
         x <- as.integer(paste0(y,"03","31"))
  }
        if(q=="Q2"){
            x <- as.integer(paste0(y,"06","30"))
  }
        if(q=="Q3"){
            x <- as.integer(paste0(y,"09","30"))
  }
        if(q=="Q4"){
           x <- as.integer(paste0(y,"12","31"))
          }       
  return(x)
}

> GetProperDate("2019Q1")
[1] 20190331
> GetProperDate("2019Q2")
[1] 20190630
> GetProperDate("2019Q3")
[1] 20190930
> GetProperDate("2019Q4")
[1] 20191231
> date.list<-c("2019Q1","2019Q2","2019Q3","2019Q4")
> date.list.converted<- date.list %>% GetProperDate()
Warning messages:
1: In if (q == "Q1") { :
  the condition has length > 1 and only the first element will be used
2: In if (q == "Q2") { :
  the condition has length > 1 and only the first element will be used
3: In if (q == "Q3") { :
  the condition has length > 1 and only the first element will be used
4: In if (q == "Q4") { :
  the condition has length > 1 and only the first element will be used
> date.list.converted
[1] 20190331 20190331 20190331 20190331
> 

如上所示,我收到一条警告消息,并且输出与预期不符。

标签: r

解决方案


问题是您编写了一个GetProperDate未矢量化的函数。if用于标量输入而不是向量。您可以切换到ifelse哪个是矢量化的并重写您的函数。

除此之外,您还可以使用as.yearqtrfrom zoo which 来处理季度日期并使用frac = 1.

as.Date(zoo::as.yearqtr(date.list), frac = 1)
#[1] "2019-03-31" "2019-06-30" "2019-09-30" "2019-12-31"

推荐阅读