Home > OS >  Is there a way to round the results of the prop.table function in R?
Is there a way to round the results of the prop.table function in R?

Time:02-15

I would like to round the results of the prop.table to one decimal place but it does not seem it work as intended. Any leads?

data(mtcars)

with(mtcars, table(vs, am)) |> prop.table(margin = 1) * 100 |> round()

CodePudding user response:

Its all about the paranthesis:

with(mtcars, table(vs, am) |> prop.table(margin = 1) * 100) |>round(1)

   am
vs     0    1
  0 66.7 33.3
  1 50.0 50.0

Note that what you have does not round the results of prop.table but rather rounds 100. If you want you could do

(with(mtcars, table(vs, am)) |> prop.table(margin = 1) * 100)|>round(1)

  am
vs     0    1
  0 66.7 33.3
  1 50.0 50.0

CodePudding user response:

We may pass a lambda expression from the output of prop.table to multiply and then round

with(mtcars, table(vs, am)) |> 
     prop.table(margin = 1) |> 
     {\(x) x * 100}() |> 
     round(digits = 1)

-output

    am
vs       0    1
  000 66.7 33.3
  001 50.0 50.0

If we load magrittr, can use alias functions

library(magrittr)
mtcars %$% 
  table(vs, am) |> 
  prop.table(margin = 1) |> 
  multiply_by(100) |>
  round(1)
     am
vs       0    1
  000 66.7 33.3
  001 50.0 50.0

CodePudding user response:

Leaving your code as is, we could set options(digits=3) default is 7:

options(digits=3)
with(mtcars, table(vs, am)) |> prop.table(margin = 1) * 100 
   am
vs     0    1
  0 66.7 33.3
  1 50.0 50.0
  •  Tags:  
  • r
  • Related