1

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?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Babai I.
  • 23
  • 1
  • 4

4 Answers4

7

We can use chartr from base R

df$Sex <- chartr("FM", "MF", df$Sex)
df$Sex
#[1] "M" "F" "M" "M" "F" "M" "F"
akrun
  • 874,273
  • 37
  • 540
  • 662
3

I think you can use ifelse here:

df$Sex <- ifelse(df$Sex == "F", "M", "F")
df

      Name Age Height Weight Sex
1     Alex  25    177     57   M
2    Lilly  31    163     69   F
3     Mark  23    190     83   M
4   Oliver  52    179     75   M
5   Martha  76    163     70   F
6    Lucas  49    183     83   M
7 Caroline  26    164     53   F

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

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)
tyluRp
  • 4,678
  • 2
  • 17
  • 36
1

When a factor, use:

df$Sex <- factor(df$Sex, c('F', 'M'), c('M', 'F'))
Axeman
  • 32,068
  • 8
  • 81
  • 94