r - 将函数应用于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
>
如上所示,我收到一条警告消息,并且输出与预期不符。
解决方案
问题是您编写了一个GetProperDate
未矢量化的函数。if
用于标量输入而不是向量。您可以切换到ifelse
哪个是矢量化的并重写您的函数。
除此之外,您还可以使用as.yearqtr
from 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"
推荐阅读
- java - BeanIo 无法读取 xml 中的特殊字符
- python - 如何在字段比较操作中,在列类型SqlAlchemy(或其他类)中实现值转换?
- r - 为什么我会收到关于奇异拟合的警告,尽管随机效应方差未估计为零,相关性也未估计为 +/- 1?
- git - Git 克隆仅适用于 git:// 而不适用于 https://
- excel - 使用 Excel::download() 方法将 excel 列设置为自动
- angular - 使用 MSAL Angular 包装器在 Ionic 4 中处理来自 Azure AD 的回调
- sql - 选择与结果匹配的 WHERE 子句
- c++ - 如何在单链表的开头插入
- three.js - 如何在 THREE.js 中的场景之间共享顶点数据?
- node.js - 如何查找我的业务何时在 google 中为 google my business api 创建