I'm trying to set the number of digits after decimal to 1. I have done this computation:
options(digits = 3)
DT<-data.table(x=c("a","b","c",NA,"b","e"),v=rnorm(6))
ans<-DT[,lapply(.SD,function(x) length(which(is.na(x)))/length(x)*100)]
Now, ans gives me the percentage of NAs in a column:
x v
16.7 0
But when I try to add the percent symbol "%" with:
ans[,lapply(.SD, function(x) paste(x,"%",sep = ''))]
The decimal digits are back there:
x v
1: 16.6666666666667% 0%
What am I doing wrong? how can I get this output?:
x v
16.7% 0%
Thank you.
We can just use sprintf
by converting it to two decimal places and concatenate with %
DT[, lapply(.SD, function(x) sprintf("%0.1f%%", 100*sum(is.na(x))/.N))]
Or we can just use format
DT[, lapply(.SD, function(x) paste0(format(100*sum(is.na(x))/.N, digits = 3), "%"))]
# x v
#1: 16.7% 0%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With