R: replace_na(df$col, '') returns '没有适用于 'replace_na' 的方法应用于 class "character" 的对象 '

R: replace_na(df$col, '') returns 'no applicable method for 'replace_na' applied to an object of class "character" '

我有一个填充了字符串和 NA 的数据框列,如下所示:

df <- data.frame(col=as.character(c(NA,'', 'text', '', NA,'text')))

在这种情况下,“ ”和 NA 都代表 NA,我正在尝试标准化,因此两者都是 NA,或者两者都是“ ”。我试过这段代码:

df$col <- replace_na(df$col, '')

还有这段代码:

df$col <- replace_na(df$col, col = c(''))

但这两种方法都会产生以下输出:

 Error in UseMethod("replace_na") : 
  no applicable method for 'replace_na' applied to an object of class "character"

我知道这是一个常见的操作,我相信解决方案很简单。用字符串替换 NA 的语法是什么? (或者,什么是标准化 ' ' 和 NA 值问题的最佳解决方案?)

试试这个:

df$col[is.na(df$col)] <- ''

tidyr::replace_na() 的参数是

function (data, replace = list(), ...) 

完整数据放在第一个参数 (data) 中,然后在第二个参数 (replace) 的列表中添加一个名称-值对。

tidyr::replace_na(df, list(col = ""))
#    col
# 1     
# 2     
# 3 text
# 4     
# 5     
# 6 text