control always goes to else in if else statement in R

I have an if else statement in an R script.The problem is based on the if condition,the control always goes to the else statement and executes it whereas the control should have stopped before based on the condition satisfaction and executed instead of always going to the else statement and executing it which is actually wrong.

fl <- list.files("C:/Users/Ritwik/Documents/R/Files",
pattern = "*.csv",
full.names = TRUE)
if(fi %in% 'Unisim'){
} else if(fi %in% 'Aspen_China'){
} else if(fi %in% 'Aspen_Munich'){
} else if(fi %in% 'Promax') {
} else {

Promax_Jan_Sept_2020_Data.csv file is present in the path mentioned in the script from where it picks up csv file based on pattern match before the if else condition.So ideally,based on the if else condition it should execute promax script based on the input file but it goes to the else statement and executes the OLI script.So what happens is it always goes to the else statement and executes the same irrespective of the conditions.

Hi @ritm,
The function basename() does NOT strip away the file extension; you need this:

fl <- c("Promax_Jan_Sept_2020_Data.csv",
#> [1] "Promax_Jan_Sept_2020_Data.csv" "Aspen_China.csv"              
#> [3] "Aspen_Munich"                  "Unisim.csv"                   
#> [5] "testing.csv"
#> [1] "Promax_Jan_Sept_2020_Data" "Aspen_China"              
#> [3] "Aspen_Munich"              "Unisim"                   
#> [5] "testing"

Created on 2021-04-20 by the reprex package (v2.0.0)

But still it goes to the else statement and executes the last condition which is wrong.It doesn't stop at the fourth condition in the if else loop where based on the promax name in the input file,it will execute the promax script.

'Promax_Jan_Sept_2020_Data' == 'Promax'

you should use regex, perhaps with some form of grep. or in this case something simple like using startswith would work

startsWith('Promax_Jan_Sept_2020_Data' ,'Promax')

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.