Alex
Alex

Reputation: 2780

Replace multiple strings in one column with other values

I have a column with dozens of different strings, but there are a handful that need to be changed while all the rest maintain the same. As a reproducible example I have the following:

set.seed(42)
x <- sample(c("a", "b", "c"), 10, replace = TRUE)
x
tibble(x) %>% dplyr::mutate(x, x = case_when(x=="a"~"Apple",
                                           x=="c"~"Cat"))

The expected output is

     x    
   <chr>
 1 Cat  
 2 Cat  
 3 Apple
 4 Cat  
 5 b   
 6 b   
 7 Cat  
 8 Apple
 9 b   
10 Cat  

but I get

     x    
   <chr>
 1 Cat  
 2 Cat  
 3 Apple
 4 Cat  
 5 NA   
 6 NA   
 7 Cat  
 8 Apple
 9 NA   
10 Cat

How do I avoid NAs when I want the original string if I did not specify a new string in place of the old string?

Upvotes: 2

Views: 3033

Answers (2)

Dylan S.
Dylan S.

Reputation: 389

The most exact answer for the question given was provided in the comments by AntoniosK as follows:

mutate(x, x = case_when(x=="a"~"Apple", x=="c"~"Cat", TRUE ~ x)) 

Which will keep all remaining values as they are. It is crucial that TRUE ~ x be the last argument in case_when() as it will match all cases and therefore any following cases will not be checked.

Upvotes: 0

Daniel
Daniel

Reputation: 2229

Alternatively to dpyr, you could try using ifelse within ifelse

ifelse(x == "a","Apple",ifelse(x == "c", "cat", x))

[1] "cat" "cat"  "Apple" "cat" "b"  "b" "cat"  "Apple" "b"  "cat"  

Upvotes: 1

Related Questions