将字符串“NULL”替换为 NA

Dou*_*Fir 2 r stringr

大多数搜索结果给了我相反的结果,将 NULL 或 NA 转换为字符串“NA”。我不希望这样,我想将 'NULL' 的字符串实例转换为 NA 但收到错误:

\n
bla <- c('foo', 'bar', NA, 'NULL')\n\nstr_replace_all(bla, 'NULL', NA)\nError: `replacement` must be a character vector\n
Run Code Online (Sandbox Code Playgroud)\n

还尝试过:

\n
str_replace_all(bla, 'NULL', NA_real_)\nError: `replacement` must be a character vector\n
Run Code Online (Sandbox Code Playgroud)\n

如何将 bla 中的 'NULL' 情况转换为 NA?

\n

[编辑]

\n

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

\n
bla <- data.frame(s = c('foo', 'bar', NA, 'NULL'), n = 1:4 )\n> bla\n     s n\n1  foo 1\n2  bar 2\n3 <NA> 3\n4 NULL 4\n> bla %>% mutate(s = str_replace_all(bla, 'NULL', NA_real_))\nError: Problem with `mutate()` input `s`.\nx `replacement` must be a character vector\n\xe2\x84\xb9 Input `s` is `str_replace_all(bla, "NULL", NA_real_)`.\n
Run Code Online (Sandbox Code Playgroud)\n

akr*_*run 5

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

bla[bla == "NULL"] <- NA
Run Code Online (Sandbox Code Playgroud)

-输出

bla
[1] "foo" "bar" NA    NA   
Run Code Online (Sandbox Code Playgroud)

使用str_replace/str_replace_all,指定正确的类型NA(默认情况下,NA是逻辑的,这将与原始向量类型发生类型冲突

根据?NA

NA 是长度为 1 的逻辑常量,其中包含缺失值指示符。NA 可以强制为除原始向量之外的任何其他向量类型。还有其他支持缺失值的原子向量类型的常量 NA_integer_、NA_real_、NA_complex_ 和 NA_character_:所有这些都是 R 语言中的保留字。

str_replace_all(bla, 'NULL', NA_character_)
[1] "foo" "bar" NA    NA   
Run Code Online (Sandbox Code Playgroud)

此外,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
Run Code Online (Sandbox Code Playgroud)