简体   繁体   中英

Nested if in loop in R for the same variable

My code looks like this:

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]

}

  }

Here all_files_a is a list of file locations of 10-k files

This is a case of nested if, however the issue here is that the variable on which the nested if is used is also changing with each nest ("item_name"), thus i know that the last nest is not working ( i have manually checked the values for the same). Can someone please suggest how to proceed in such cases (specifically where the if condition is applied on a variable which is updating with each nest.

Thanks

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]
    
  }
}

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM