r - R中循环内的多个if语句
问题描述
我有一个 R 脚本,它从我的 Outlook 中的每日电子邮件中检索 CSV 文件,然后根据电子邮件主题中的日期是否大于设定日期,将它们移动到特定文件夹。该代码正在拆分主题行以提取日期 - 由于最近的更改,日期的位置可以在字符串中的两个位置之一。
我构建了一个 if 语句,它可以在任何一种情况下成功地在字符串中定位日期,但是我不能使用第二个 if 语句来查看第一个 if 语句的输出是否大于示例日期。
下面是我试图执行的代码(我已经包含了可以复制的数据):
# Test data
testLoop <- c("[EXTERNAL] Test Promo Sessions was executed at 28062019 100005",
"[EXTERNAL] Test Promo Sessions was executed at 29062019 100023",
"Test Promo Sessions was executed at 30062019 100007",
"Test Promo Sessions was executed at 01072019 100043",
"Test Promo Sessions was executed at 02072019 100049",
"Test Promo Sessions was executed at 03072019 100001")
# Example date
todaysDateFormatted2 <- '30062019'
# Loop
for(i in testLoop){
if(if(nchar(i) == 51){
strptime(sapply(strsplit(i, "\\s+"), "[", 7),"%d%m%Y")
} else {
strptime(sapply(strsplit(i, "\\s+"), "[", 8),"%d%m%Y")
} > strptime(todaysDateFormatted2,"%d%m%Y")){
print("greater than - move file")
} else {
print("not greater than - do nothing")
}
}
尝试执行此代码时,我收到以下错误,但是我不确定如何解释它:
[1] "not greater than - do nothing"
[1] "not greater than - do nothing"
Error in if (if (nchar(i) == 51) { :
argument is not interpretable as logical
In addition: Warning message:
In if (if (nchar(i) == 51) { :
the condition has length > 1 and only the first element will be used
解决方案
您的代码中有几个缺陷。重复if
的很奇怪,strptime
如果你不把它分配给下面的东西,你就无处可去t
。此外,您可能希望将else
条件分配给t
. 现在您可以比较t
并todaysDateFormatted2
打印每次迭代的结果。
for (i in testLoop) {
if (nchar(i) == 51) {
t <- strptime(sapply(strsplit(i, "\\s+"), "[", 7),"%d%m%Y")
} else {
t <- strptime(sapply(strsplit(i, "\\s+"), "[", 8),"%d%m%Y")
}
if (t > strptime(todaysDateFormatted2,"%d%m%Y")) {
print("greater than - move file")
} else {
print("not greater than - do nothing")
}
}
# [1] "not greater than - do nothing"
# [1] "not greater than - do nothing"
# [1] "not greater than - do nothing"
# [1] "greater than - move file"
# [1] "greater than - move file"
# [1] "greater than - move file"
推荐阅读
- c++ - 从向量中的父基转换的模板化子 T 生成的虚假字符
- django - 来自 docker 容器的 Django loaddata 命令
- python - 无法在 MacOS 上安装 scikits.talkbox
- r - 测试连续 5 天或更长时间向东吹的时间段的频率显着增加
- python - 如何使用 JSON 正文发送 POST 请求?
- r - 在 mac osx 中使用 RcppArmadillo 代码构建包时出现编译错误
- mysql - 我需要关于 sql 查询的解决方案和解释
- google-chrome-extension - Google Analytics(分析)测量协议并非仅在实时报告中
- javascript - LeafletJS 用压扁的瓷砖渲染
- android - Android中的分页库