0

I am trying to find an elegant way to use %in% and str_replace() to clean up gender. I know I can use regx() to do the same thing, but am looking at alternative ways to tackle the same problem.

My code is:

sex <- c("Male","girl","boy", "female")
male <- c("Male", "boy")
female <- c("girl", "female")

I know this code isn't right, but illustrates what I am trying to do

str_replace(sex, sex %in% male, "M")
str_replace(sex, sex %in% female, "F")

Any tips?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
richcru
  • 3
  • 1
  • 3

1 Answers1

0

You can do this with replace, not str_replace:

sex <- c("Male","girl","boy", "female")
male <- c("Male", "boy")
female <- c("girl", "female")

sex <- replace(sex, which(sex %in% male), "M")
sex <- replace(sex, which(sex %in% female), "F")
sex
#> [1] "M" "F" "M" "F"

Created on 2018-10-28 by the reprex package (v0.2.1)

Calum You
  • 14,687
  • 4
  • 23
  • 42