将字符串 'NULL' 替换为 NA

Replace string 'NULL' with NA

大多数搜索结果给我相反的结果,将 NULL 或 NA 变成字符串 'NA'。我不想这样,我想将 'NULL' 的字符串实例转换为 NA 但出现错误:

bla <- c('foo', 'bar', NA, 'NULL')

str_replace_all(bla, 'NULL', NA)
Error: `replacement` must be a character vector

也尝试过:

str_replace_all(bla, 'NULL', NA_real_)
Error: `replacement` must be a character vector

如何在 bla 中将 'NULL' 的大小写转换为 NA?

[编辑]

明确地说,我实际上是在 dplyr 链中执行此操作,例如

bla <- data.frame(s = c('foo', 'bar', NA, 'NULL'), n = 1:4 )
> bla
     s n
1  foo 1
2  bar 2
3 <NA> 3
4 NULL 4
> bla %>% mutate(s = str_replace_all(bla, 'NULL', NA_real_))
Error: Problem with `mutate()` input `s`.
x `replacement` must be a character vector
ℹ Input `s` is `str_replace_all(bla, "NULL", NA_real_)`.

只需使用 == 而不是正则表达式子字符串替换

bla[bla == "NULL"] <- NA

-输出

bla
[1] "foo" "bar" NA    NA   

使用 str_replace/str_replace_all,为 NA 指定正确的类型(默认情况下,NA 是合乎逻辑的,这会与原始向量类型

发生类型冲突

根据?NA

NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw. There are also constants NA_integer_, NA_real_, NA_complex_ and NA_character_ of the other atomic vector types which support missing values: all of these are reserved words in the R language.

str_replace_all(bla, 'NULL', NA_character_)
[1] "foo" "bar" NA    NA   

此外,str_replace主要用于子字符串替换而不是固定的完整字符串替换(因为我们可能会发现效率也会降低)


tidyverse里面还有na_if

library(dplyr)
bla %>% 
    mutate(s = na_if(s, "NULL"))
     s n
1  foo 1
2  bar 2
3 <NA> 3
4 <NA> 4