0

I have below R code which will iterate each text file which then fetches the respective parameter from each file and append it to the data frame.

Once the lapply get's over. I need a consolidated data frame in Final

How do I achieve this

files <- list.files(path="D:/Test/R/PBC", pattern="*.txt", full.names=TRUE, recursive=FALSE)

lapply(files, function(x) {

        text <- x       
        
        policy_nr <- str_extract(text,"(?<=Contract Number \\: )\\d+")
        
        if( is.na(policy_nr) == TRUE )
        {
          policy_nr <- str_extract(text,"(?<=Policy Number \\: )\\d+")
        }

        advisor_code <- str_extract(text,"(?<=Advisor Code \\: )\\d+")

        if( is.na(advisor_code) == TRUE )
        {
          advisor_code <- str_extract(text,"(?<=Advisor Code: )\\d+")
        }       

        data <- data.frame(PolicyNumber=policy_nr,AdvisorCode=advisor_code)
        
        


}
)

Final <- ?
Chennai Cheetah
  • 333
  • 1
  • 7

1 Answers1

1
files <- list.files(path="D:/Test/R/PBC", pattern="*.txt", full.names=TRUE, recursive=FALSE)

process <- lapply(files, function(text) {
  
  policy_nr <- str_extract(text,"(?<=Contract Number \\: )\\d+")

  if (is.na(policy_nr)) {
    policy_nr <- str_extract(text,"(?<=Policy Number \\: )\\d+")
  }

  advisor_code <- str_extract(text,"(?<=Advisor Code \\: )\\d+")

  if (is.na(advisor_code)) {
    advisor_code <- str_extract(text,"(?<=Advisor Code: )\\d+")
  }
  
  data.frame("PolicyNumber" = policy_nr, "AdvisoryCode" = advisor_code)
  
})

Final <- do.call(rbind, process)
Merijn van Tilborg
  • 3,487
  • 1
  • 4
  • 15
  • Hi Merjin.. Any Ideaa how to move current file to Working directory sub folder named Success..... if ( is.na(policy_nr) && is.na(advisor_code) ) { file_move("x","/Success") } .. I tried this ..but no luck – Chennai Cheetah Dec 02 '21 at 15:16
  • Try not to make one specific question an ongoing process of all questions you encounter to get your final solution along the road. Have you tried to simply move any file to test your code. Simply make a test file and try to move it to another folder. – Merijn van Tilborg Dec 02 '21 at 15:33