首页 > 解决方案 > 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

标签: rloopsif-statement

解决方案


您的代码中有几个缺陷。重复if的很奇怪,strptime如果你不把它分配给下面的东西,你就无处可去t。此外,您可能希望将else条件分配给t. 现在您可以比较ttodaysDateFormatted2打印每次迭代的结果。

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"

推荐阅读