15

A traditional way of making a table in R:

data(mtcars)

round(100*prop.table(xtabs(~ gear + cyl, data = mtcars), 1), 2)

returns

   cyl
gear     4     6     8
  3  6.67 13.33 80.00
  4 66.67 33.33  0.00
  5 40.00 20.00 40.00

To replicate this using the magrittr pipes, I've tried:

library(magrittr)

mtcars %>%
 xtabs(~ gear + cyl, data = .) %>%
 prop.table(., 1)

which works great up to this point

    cyl
gear          4          6          8
   3 0.06666667 0.13333333 0.80000000
   4 0.66666667 0.33333333 0.00000000
   5 0.40000000 0.20000000 0.40000000

but any attempt to perform the next part, wherein I convert proportions to percentages, and then round, results in an error. For instance:

mtcars %>%
  xtabs(~ gear + cyl, data = .) %>%
  100*prop.table(., 1)

and

mtcars %>%
  xtabs(~ gear + cyl, data = .) %>%
  prop.table(., 1) %>%
  100 * .

all result in an error. What am I missing?

tomw
  • 3,114
  • 4
  • 29
  • 51
  • 3
    In your example, the margin was for rows, In the `magrittr`, you are using `columns`. `mtcars %>% xtabs(~gear+cyl, data=.) %>% prop.table(.,1) %>% multiply_by(100) %>% round(., 2)` – akrun Jan 26 '15 at 18:22
  • 1
    see http://stackoverflow.com/a/27364575/3871924 – agenis Jan 26 '15 at 18:22
  • @akrun--thanks for the catch, corrected above. – tomw Jan 26 '15 at 18:25

1 Answers1

30

You need to put * in quotes - "*"(), also use 1 as your argument in prop.table to match the example.

mtcars %>%
  xtabs(~ gear + cyl, data = .) %>%
  prop.table(., 1) %>%
  "*"(100 ) %>% round(.,2)
John Paul
  • 12,196
  • 6
  • 55
  • 75