如何正确处理 NA 强制警告

How do I correctly handle NA coercion warning

我想将一列从字符转换为数字。无法转换某些值。这会导致警告,这是预期的行为。

data.frame(a=c("5","7","not_a_number"),stringsAsFactors = F) %>% mutate(value=as.numeric(a))

此外,我还有另一列提供信息,哪些行可以转换为数字(逻辑)。我想使用此列,以便 R 可以确定它不必强制执行。

data.frame(a=c("5","7","not_a_number"),b=c(1,1,0),stringsAsFactors = F) %>% 
mutate(value=ifelse(b,as.numeric(a),NA_integer_))

但这给出了同样的错误。为什么?这里不应该强迫任何东西。我正在处理并负责跨行的正确和兼容类型。发生了什么事?

您需要在 ifelse 之外申请 as.numeric :

library(dplyr)
df %>% mutate(value = as.numeric(ifelse(b,a,NA)))

#             a b value
#1            5 1     5
#2            7 1     7
#3 not_a_number 0  <NA>

其中 df 是:

df <- data.frame(a=c("5","7","not_a_number"),b=c(1,1,0),stringsAsFactors = FALSE) 

间接答案,为什么不在转换为数字之前删除所有 non-digits:

data.frame(a = c("5","7","not_a_number"), stringsAsFactors = FALSE) %>%
  mutate(value = as.numeric(gsub("\D+", "", a)))
#              a value
# 1            5     5
# 2            7     7
# 3 not_a_number    NA