[英]R: as.character removes trailing zeros of numbers. How to avoid
I have我有
kappa<-c(0.10, NA, 0.0740)
When I do当我做
kappa %>% replace(is.na(.), "")
I get我得到
> kappa %>% replace(is.na(.), "")
[1] "0.1" "" "0.074"
The same when I do我做的时候也一样
> as.character(kappa)
[1] "0.1" NA "0.074"
How can I avoid (in the remove()
case) the removal of the trailing zero?如何避免(在
remove()
情况下)删除尾随零? I would like to result to the following vector我想得到以下向量
"0.10", NA, "0.0740"
You are looking for format()
with a nsmall
argument as the number of digits.您正在寻找带有
nsmall
参数作为位数的format()
。
This number can be computed as the maximum of the base 10 logarithm of your numeric vector (but you obviously can enter any arbitrary value).该数字可以计算为数值向量以 10 为底的对数的最大值(但显然您可以输入任意值)。
Here is the code:这是代码:
kappa = c(0.10, NA, 0.0740)
n_digits = max(abs(log(kappa)), na.rm=TRUE)
format(kappa, nsmall=n_digits)
#> [1] "0.100" " NA" "0.074"
Created on 2022-12-13 with reprex v2.0.2创建于 2022-12-13,使用reprex v2.0.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.