0

I have a column in a data frame that looks like this:

    Category      X        Y
        M         45       56
        F         45       54
        O         23       56

I want to replace M, F and O with Male, Female and Other.

Rnovice
  • 59
  • 6
  • ok.. this should not be too hard. What have you tried and wasn't working as expected? – Wimpel Mar 11 '21 at 14:28
  • I used df[1,1] = Male, df[2,1]= female and df[3,1]= other, but I'd like to know if this is possible in a single line of code – Rnovice Mar 11 '21 at 14:36
  • 1
    have you tried solutions from https://stackoverflow.com/questions/50898623/how-to-replace-multiple-values-at-once ? – Wimpel Mar 11 '21 at 14:37
  • Does this work? `df[, 1] <- c("Male", "Female", "Other")` – dcarlson Mar 11 '21 at 20:06

2 Answers2

0

You can use the code below:

Category<-c("M","F","O")
X<-c(45,45,23)
Y<-c(56,54,56)
df<-data.frame(Category, X, Y)
df <- data.frame(lapply(df, function(x) {gsub("M", "Male", x)}))
df <- data.frame(lapply(df, function(x) {gsub("F", "Female", x)}))
df <- data.frame(lapply(df, function(x) {gsub("O", "Other", x)}))
doctshind s
  • 380
  • 3
  • 13
0

A solution with dplyr

library(dplyr)
df <- df %>% 
  mutate(Category = recode(Category, "M" = "Male", "F" = "Female", "O" = "Other"))
TarJae
  • 72,363
  • 6
  • 19
  • 66