我有一个数据框,其中的字符变量主要由数值组成,偶尔会有已知的字符串以及一些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>
Run Code Online (Sandbox Code Playgroud)
但是会发出警告信息
Warning message:
In format(round(as.numeric(c("1", "2", "3", "none", NA)), 1), nsmall = 1) :
NAs introduced by coercion
Run Code Online (Sandbox Code Playgroud)
我相信b/c format(round(as.numeric(a), 1), nsmall = 1)))仍然作用于整个向量,即使其中的值仅用于条件为false 的mutate语句中ifelse.
我可以将整个内容包装起来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>
Run Code Online (Sandbox Code Playgroud)