R - dplyr在自身条件下发生突变



我有一个数据帧,其中字符变量主要由数值组成,偶尔有已知字符串以及一些NA值。我想有条件地重新格式化数值,使其具有一个小数点,但保留字符和NA值。

这段代码在一个玩具数据帧上工作,并产生所需的输出:

df <- data.frame(a = c("1", "2", "3", "none", NA),
                 stringsAsFactors = FALSE)
test <- df %>%
  mutate(a = ifelse(is.na(a) | a == "none",
                    a,
                    format(round(as.numeric(a), 1), nsmall = 1)))
test
#    a
# 1  1.0
# 2  2.0
# 3  3.0
# 4 none
# 5 <NA>

但是抛出警告消息

Warning message:
In format(round(as.numeric(c("1", "2", "3", "none", NA)), 1), nsmall = 1) :
  NAs introduced by coercion

,我认为是b/c format(round(as.numeric(a), 1), nsmall = 1)))的情况下仍然作用于整个向量,即使只有在ifelse条件为假的mutate语句中使用的值。

我可以包装整个事情在suppressWarnings(),但是有没有其他的方式来产生所需的输出没有警告在dplyr框架内?我相信有一个data.table的方法来做到这一点,但这是一个包的一部分,不需要data.table的其他任何东西,这似乎是愚蠢的,使它必须为这样一个小块…

使用replace,您可以仅转换a列中的数字类型数据:

test <- df %>%
    mutate(a = replace(a, !is.na(a) & a != "none",
                       format(round(as.numeric(a[!is.na(a) & a != "none"]), 1), nsmall = 1)))
test
#     a
#1  1.0
#2  2.0
#3  3.0
#4 none
#5 <NA>

最新更新