将函数应用于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
> 

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

Zhiqiang Wang

尝试这个:

library(tidyverse)
GetProperDate <- function(x) {
  x <- as.character(x)
  q <- substr(x, 5, 6)
  y <- substr(x, 1,4) %>% 
    as.numeric()
  x <- case_when(
    q=="Q1" ~ as.integer(paste0(y,"03","31")), 
    q =="Q2" ~ as.integer(paste0(y,"06","30")), 
    q == "Q3" ~ as.integer(paste0(y,"09","30")), 
   TRUE ~ as.integer(paste0(y,"12","31")))
  return(x)
}
date.list<-c("2019Q1","2019Q2","2019Q3","2019Q4")
GetProperDate(date.list) 

>  GetProperDate(date.list) 
[1] 20190331 20190630 20190930 20191231

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将函数(AIC)应用于列表中的元素

将方法应用于浮点数数组流时出现问题?

将函数应用于R中的列表矩阵

将函数列表应用于Ramda中的值

将函数应用于R中的数据帧列表

R:将函数应用于长度可变的嵌套列表

将dplyr函数中包含group_by的函数应用于R中的数据列表

SceneKit在将纹理应用于自定义几何体时出现问题

将dplyr函数中的purrr :: map应用于列表

在Pyspark中将UDF余弦相似度应用于分组的ML向量时出现问题

使用numpy将二进制蒙版应用于RGB图像时出现问题

R使用“ [[”将函数应用于嵌套列表元素

dplyr出现问题(将which.min应用于数据帧列表)

将lambda函数应用于pandas中的列时出现“ IndexError:列表索引超出范围”

将函数应用于Pandas行中的值列表

将筛选器应用于列表后,TextWatcher和ListView元素的位置出现问题

在将装饰器设计模式应用于JavaScript代码时出现问题

R将栅格函数应用于字符列表

将函数应用于列表中的列表

将公式应用于整个列:表格中的arrayformula出现问题

当 ":invalid" 样式应用于表单控件时,表格列宽出现问题

将函数应用于来自不同列表的元素时出现的问题

将函数应用于嵌套 r 的列表的每个元素

R - Purrr - 将函数应用于列表中的 Tibbles

将函数应用于多个列表 (R)

将循环应用于 r 中的列表列表

R:将函数应用于嵌套列表

R - 将函数应用于 lm 摘要列表

将多参数函数应用于 R 中列表中的所有数据框