How to round all prop.table values ​​in R in one line?

In R 3.4.0, how can I round off all the percentages generated by prop.table () to 3 decimal places on one line?

This does not work:

MyTable$MyCol %>% table() %>% prop.table()*100 %>% round(.,3)

        -7          -2          0          1          2          3         4         5 
 0.4672897  0.2336449 31.7757009  1.6355140 44.3925234 20.3271028  0.4672897  0.7009346 

expected something like:

   -7     -2    0       1      2     3       4      5 
 0.467  0.233 31.775 1.635 44.392 20.327  0.467  0.700 
+4
source share
4 answers

You need to divide the multiplication into a separate operation:

mtcars$cyl %>% table() %>% prop.table() %>% `*`(100) %>% round(2)
+3
source

We can also use {}to evaluate ( ...) as a whole within the range %>% ... %>%to the next%>%

mtcars$cyl %>%
   table() %>%
   prop.table() %>% {. * 100} %>% 
   round(2)
.
#     4     6     8 
# 34.38 21.88 43.75 
+2
source

a <- c(0.4, 0.2336449, 31.7757009, 1.6355140, 44.3925234, 20.3271028, 0.4672897, 0.7)

format(round(a, 3), nsmall = 3)
# [1] " 0.400" " 0.234" "31.776" " 1.636" "44.393" "20.327" " 0.467" " 0.700"

options(digits=3)
a
# [1]  0.400  0.234 31.776  1.636 44.393 20.327  0.467  0.700
+1

R 3.5.1 :

data=sample(1:5, 100, replace=T)

round(prop.table(table(data)),3)

#data
#   1    2    3    4    5 
#0.16 0.24 0.16 0.18 0.26

-, , , .

0

Source: https://habr.com/ru/post/1682552/


All Articles