Replace characters on data

Viewed 51

for example i want to replace the character "A" for "Apple" and the character "B" for "Bannana"

junk <- data.frame(x = rep(LETTERS[1:4], 3), 
                   y = letters[1:12],
                   stringsAsFactors = FALSE)

this provides:

   x y
1  A a
2  B b
3  C c
4  D d
5  A e
6  B f
7  C g
8  D h
9  A i
10 B j
11 C k
12 D l

I tried to use

library(dplyr)
library(stringr)

mutate_if(junk, 
          is.character, 
          str_replace_all, pattern = "A", replacement = "Apple")

However i when i tried to do the same with "B" it removes the previous replacement for "A". And i want to keep both results.

mutate_if(junk, 
          is.character, 
          str_replace_all, pattern = "A", replacement = "Apple") 

I want to keep both results "Apple" and "Bannana"

2 Answers

You are probably looking for:

junk %>%
 mutate_if(is.character, str_replace_all, c("A" = "Apple", "B" = "Banana"))

        x y
1   Apple a
2  Banana b
3       C c
4       D d
5   Apple e
6  Banana f
7       C g
8       D h
9   Apple i
10 Banana j
11      C k
12      D l

Use dplyr and case_when:

junk %>% mutate(nm = case_when(
  nm == "A" ~ "Apple",
  nm == "B" ~ "Banana",
  TRUE ~ nm
))

As suggested by @d.b, you can also use:

junk %>% mutate(nm = recode(nm, A = "Apple", B = "Banana"))
Related