rstringswapchars

Swap chars or strings in data.frame


I have a data.frame with column of Sex:

Name <- c("Alex", "Lilly", "Mark", "Oliver", "Martha", "Lucas", "Caroline")
Age <- c(25, 31, 23, 52, 76, 49, 26)
Height <- c(177, 163, 190, 179, 163, 183, 164)
Weight <- c(57, 69, 83, 75, 70,  83, 53)
Sex <- c("F", "M", "F", "F", "M", "F", "M")

As you can see, the sex is incorrect (for example, Lilly's sex is 'M') and I want to swap all the 'F's to 'M's and all the 'M's to 'F's.

Is there a function for that?


Solution

  • Alternatively, with dplyr we can use case_when:

    library(dplyr)
    
    df %>% 
      mutate(Sex = case_when(Sex == "F" ~ "M",
                             Sex == "M" ~ "F",
                             TRUE ~ NA_character_))
    

    Data:

    Name <- c("Alex", "Lilly", "Mark", "Oliver", "Martha", "Lucas", "Caroline") 
    Age <- c(25, 31, 23, 52, 76, 49, 26) 
    Height <- c(177, 163, 190, 179, 163, 183, 164) 
    Weight <- c(57, 69, 83, 75, 70, 83, 53) 
    Sex <- c("F", "M", "F", "F", "M", "F", "M")
    
    df <- data.frame(Name, Age, Height, Weight, Sex)