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.

getwd()
setwd("C:/Users/Ritwik/Documents/R/Files")
fl <- list.files("C:/Users/Ritwik/Documents/R/Files",
pattern = "*.csv",
full.names = TRUE)
fl
basename(fl)
fi<-basename(fl)
if(fi %in% 'Unisim'){
source("C:/Users/Ritwik/Documents/R/Unisim_Shiny_App.R")$value
} else if(fi %in% 'Aspen_China'){
source("C:/Users/Ritwik/Documents/R/Aspen_China_Shiny_App.R")$value
} else if(fi %in% 'Aspen_Munich'){
source("C:/Users/Ritwik/Documents/R/Aspen_Munich_Shiny_App.R")$value
} else if(fi %in% 'Promax') {
source("C:/Users/Ritwik/Documents/R/Promax_Shiny_App.R")$value
} else {
source("C:/Users/Ritwik/Documents/R/OLI_Shiny_App.R")$value
}

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",
        "Aspen_China.csv",
        "Aspen_Munich",
        "Unisim.csv",
        "testing.csv")
basename(fl)
#> [1] "Promax_Jan_Sept_2020_Data.csv" "Aspen_China.csv"              
#> [3] "Aspen_Munich"                  "Unisim.csv"                   
#> [5] "testing.csv"
tools::file_path_sans_ext(fl)
#> [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'
# FALSE

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')
# TRUE

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.