Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to set number of digits after decimal using paste function (R)

Tags:

r

decimal

paste

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.

like image 666
La Machine Infernale Avatar asked Dec 23 '22 18:12

La Machine Infernale


1 Answers

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%
like image 60
akrun Avatar answered Apr 30 '23 19:04

akrun