Home > Mobile >  How to create a `if` statement dynamically in R?
How to create a `if` statement dynamically in R?

Time:08-17

How to make the following code more concise, so as not to repeat the if statement three times?

txtA <- "text A"
txtB <- "text B"
txtC <- "text C"

section <- "B"

# How to make the following code in a more programmatic manner?
if (section == "A") txtA <- tolower(txtA)
if (section == "B") txtB <- tolower(txtB)
if (section == "C") txtC <- tolower(txtC)

I don't expect a simple dplyr::case_when but something that also does the txtXX <- tolower(txtXX) more general.

CodePudding user response:

Not sure, if I got your goal correct and you simply want to get rid of the explicit if statements? I would suggest collecting all 'paragraphs' in a single object first for easier handling.

all_txt <- list(
  A = "text A",
  B = "text B",
  C = "text C"
)
section <- 'B'
all_txt[[section]] <- tolower(all_txt[[section]])
all_txt 
  • Related