简体   繁体   English

如何用 NA、na_if、if_else、regex 替换某些字符串

[英]How to replace certain strings with NA, na_if, if_else, regex

I have a character variable that has some values that I want replaced by NA (eg "N/A"; "NA" entered as text, not R's NA type; other text responses.) The values I don't want replaced by NA contain number strings, so I tried using a regular expression to select the non-number strings to replace with NA.我有一个字符变量,它有一些我想用 NA 替换的值(例如“N/A”;“NA”作为文本输入,而不是 R 的 NA 类型;其他文本响应。)我不想用 NA 替换的值包含数字字符串,所以我尝试使用正则表达式来选择非数字字符串替换为 NA。

I'm able to filter for the non-number cases using the following, or the number string cases if I remove the "!".我可以使用以下内容过滤非数字案例,或者如果我删除“!”,则可以过滤数字字符串案例。 I'm been unable to figure out how to use mutate() with if_else() and str_detect() or na_if() with str_detect() to replace these cases.我一直无法弄清楚如何将 mutate() 与 if_else() 和 str_detect() 或 na_if() 与 str_detect() 一起使用来替换这些情况。 I've only been able to replace cases if I specify them exactly with na_if().如果我用 na_if() 准确指定它们,我只能替换它们。

library(dplyr)
library(stringr)

df <- data.frame(var1 = c("84950", "NA", "N/A", "84596/03456", "55555", NA), 
                 var2 = rep("10000", 6))

df %>% 
  filter(!str_detect(var1, "[:digit:]"))

This doesn't work.这行不通。

df %>% 
mutate(var1 = if_else(str_detect(var1, "[:digit:]"), var1, NA))

This doesn't work, leaves all the cases as is.这不起作用,让所有情况保持原样。

df %>% 
  mutate(var1 = na_if(var1, !str_detect(var1, "[:digit:]"))) 

This works to replace this particular value "N/A"这可以替换这个特定值“N/A”

df %>% 
  mutate(var1 = na_if(var1, "N/A"))

Your second approach is close.你的第二种方法很接近。 You would need to specify that NA is a character type.您需要指定NA是一种字符类型。

df |>
  mutate(var1 = if_else(str_detect(var1, "[:digit:]"), var1, NA_character_))

Output:输出:

         var1  var2
1       84950 10000
2        <NA> 10000
3        <NA> 10000
4 84596/03456 10000
5       55555 10000
6        <NA> 10000

Here is an alternative approache using %in% operator:这是使用%in%运算符的替代方法:

library(dplyr)
df %>% 
  mutate(var1 = ifelse(var1 %in% c("N/A", "NA"), NA_character_, var1))
         var1  var2
1       84950 10000
2        <NA> 10000
3        <NA> 10000
4 84596/03456 10000
5       55555 10000
6        <NA> 10000

Another option using replace like this:使用这样的replace的另一个选项:

library(dplyr)

df <- data.frame(var1 = c("84950", "NA", "N/A", "84596/03456", "55555", NA), 
                 var2 = rep("10000", 6))

df %>%
  mutate(across(var1, ~ replace(., . %in% c("N/A", "NA"), NA)))
#>          var1  var2
#> 1       84950 10000
#> 2        <NA> 10000
#> 3        <NA> 10000
#> 4 84596/03456 10000
#> 5       55555 10000
#> 6        <NA> 10000

Created on 2022-07-15 by the reprex package (v2.0.1)reprex 包于 2022-07-15 创建 (v2.0.1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM