-4

I have a dataset something like this:

dataset

How can I replace all the Male into Female using r?

Jaap
  • 81,064
  • 34
  • 182
  • 193
  • 1
    Do not post your data as an image, please learn how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – Jaap Feb 26 '17 at 14:39

2 Answers2

2

First, welcome to Stackoverflow. As pointed in the comments, it's better to give a reproducible example. I'm happy to answer this time, but bear in mind that in the future, you are more likely to get answers if you give such an example.

I'm assuming you're working with a data frame. What you would need is:

> df <- data.frame("name"=c("A","B","C","D"), sex=c("Male","Male","Male","Female"))
> df
  name    sex
1    A   Male
2    B   Male
3    C   Male
4    D Female
> df$sex[df$sex == "Male"] <- "Female"
> df
  name    sex
1    A Female
2    B Female
3    C Female
4    D Female

The line df$sex[df$sex == "Male"] <- "Female" is what you are looking for. The first part, df$sex, selects the column named sex.

The second part, [df$sex == "Male"], selects all rows of the column which have sex equal to "Male".

The last part is assignment. <- "Female" assigns selected observations the value "Female".

wwl
  • 2,025
  • 2
  • 30
  • 51
1

We can use

library(data.table)
setDT(df)[sex=="Male", sex := "Female"]

Or using base R

df$sex <- with(df, replace(sex, sex=="Male", "Female"))
akrun
  • 874,273
  • 37
  • 540
  • 662