I have a dataset something like this:
How can I replace all the Male into Female using r?
I have a dataset something like this:
How can I replace all the Male into Female using r?
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".
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"))