gpt4 book ai didi

将字符串 'NULL' 替换为 NA

转载 作者:行者123 更新时间:2023-12-03 08:19:22 25 4
gpt4 key购买 nike

大多数搜索结果给了我相反的结果,将 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

关于将字符串 'NULL' 替换为 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68332117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com