我有一列包含许多不同字符串的列,但是有一些需要更改,而其余所有字符串都保持不变。作为可复制的示例,我有以下内容:
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"))
预期的输出是
x
<chr>
1 Cat
2 Cat
3 Apple
4 Cat
5 b
6 b
7 Cat
8 Apple
9 b
10 Cat
但我明白了
x
<chr>
1 Cat
2 Cat
3 Apple
4 Cat
5 NA
6 NA
7 Cat
8 Apple
9 NA
10 Cat
NA
如果我未指定新字符串代替旧字符串,如何在想要原始字符串时避免s?
除了dpyr
,您可以尝试ifelse
在ifelse
ifelse(x == "a","Apple",ifelse(x == "c", "cat", x))
[1] "cat" "cat" "Apple" "cat" "b" "b" "cat" "Apple" "b" "cat"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句