OneBite.Dev - Coding blog in a bite size

convert variable from string to boolean in R

Code snippet on how to convert variable from string to boolean in R

  parse_bool <- function(s) {
    s <- tolower(s)
    if (s == "true") return(TRUE)
    if (s == "false") return(FALSE)
    warning("Input '", s, "' is not TRUE/FALSE, returning NA")
    return(NA)
  }

This code creates a function called parse_bool which can convert a string variable to a boolean. The function takes an input string s and converts it to lowercase with the tolower function. Then it checks if the string has a value of true or false, and if it does, it returns the matching boolean of TRUE/FALSE respectively. If the input is neither of these values, it will give a warning and return NA.

r