【问题标题】:Nested if in loop in R for the same variable嵌套在R中的循环中,用于相同的变量
【发布时间】:2020-11-20 09:34:35
【问题描述】:

我的代码如下所示:

MDA = NULL;

for (i in 1:10) 

{
print(i)

test_10k = edgarWebR::parse_text_filing(readtext::readtext(all_files_a[[i]])$text)

item_name = grep("Discussion and Analysis of Financial Condition and Results of Operation",  test_10k$item.name, ignore.case = TRUE)

MDA[[i]]  = test_10k$text[item_name]

if(rlang::is_empty(item_name) == TRUE){

  test_10k = edgarWebR::parse_text_filing(readtext::readtext(all_files_a[[i]])$text, strip = FALSE, include.raw = TRUE)

  item_name = grep("DISCUSSION AND ANALYSIS OF FINANCIAL CONDITION AND RESULTS OF OPERATION",  test_10k$raw, ignore.case = FALSE)

  MDA[[i]]  = test_10k$text[item_name]

}
else if(rlang::is_empty(item_name) == TRUE){

  test_10k = edgarWebR::parse_text_filing(readtext::readtext(all_files_a[[i]])$text, strip = FALSE, include.raw = TRUE)

  item_name = grep("DISCUSSION AND ANALYSIS AND RESULTS OF OPERATIONS",  test_10k$item.name, ignore.case = FALSE)

  MDA[[i]]  = test_10k$text[item_name]

}

  }

这里 all_files_a 是 10-k 个文件的文件位置列表

这是嵌套 if 的情况,但是这里的问题是使用嵌套 if 的变量也随着每个嵌套(“item_name”)而变化,因此我知道最后一个嵌套不起作用(i已手动检查相同的值)。有人可以建议在这种情况下如何进行(特别是 if 条件应用于每个嵌套更新的变量。

谢谢

【问题讨论】:

  • 发现了我的错误,第二个 else if 将是 if 并且会写在第一个 if 中,像这样:

标签: r loops nested-if


【解决方案1】:
MDA = NULL;



for (i in 1:10) {
print(i)
test_10k = edgarWebR::parse_text_filing(readtext::readtext(all_files_a[[i]])$text)
item_name = grep("Discussion and Analysis of Financial Condition and Results of Operation",  test_10k$item.name, ignore.case = TRUE)
MDA[[i]]  = test_10k$text[item_name]
if(rlang::is_empty(item_name) == TRUE){
  test_10k = edgarWebR::parse_text_filing(readtext::readtext(all_files_a[[i]])$text, strip = FALSE, include.raw = TRUE)
  item_name = grep("DISCUSSION AND ANALYSIS OF FINANCIAL CONDITION AND RESULTS OF OPERATION",  test_10k$raw, ignore.case = FALSE)
  MDA[[i]]  = test_10k$text[item_name]
  if(rlang::is_empty(item_name) == TRUE){
    test_10k = edgarWebR::parse_text_filing(readtext::readtext(all_files_a[[i]])$text, strip = FALSE, include.raw = TRUE)
    item_name = grep("DISCUSSION AND ANALYSIS AND RESULTS OF OPERATIONS",  test_10k$item.name, ignore.case = FALSE)
    MDA[[i]]  = test_10k$text[item_name]
    
  }
}

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2020-04-12
    • 2018-06-11
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多