将一列中的多个字符串替换为其他值

时间:2022-10-05 07:55:50

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?

如果我没有指定新字符串代替旧字符串,如何在需要原始字符串时如何避免使用NA?

1 个解决方案

#1


0  

Alternatively to dpyr, you could try using ifelse within ifelse

作为dpyr的替代方案,您可以尝试在ifelse中使用ifelse

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

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

#1


0  

Alternatively to dpyr, you could try using ifelse within ifelse

作为dpyr的替代方案,您可以尝试在ifelse中使用ifelse

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

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