Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do multiplication with magrittr pipes [duplicate]

Tags:

r

magrittr

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?

like image 944
tomw Avatar asked Jan 26 '15 18:01

tomw


People also ask

What does this %>% mean in R?

%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. It is defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

What does Magrittr do in R?

The magrittr package offers a set of operators which make your code more readable by: structuring sequences of data operations left-to-right (as opposed to from the inside and out), avoiding nested function calls, minimizing the need for local variables and function definitions, and.

What are pipes R?

What does the pipe do? The pipe operator, written as %>% , has been a longstanding feature of the magrittr package for R. It takes the output of one function and passes it into another function as an argument. This allows us to link a sequence of analysis steps.

What is the purpose of the pipe operator?

What is the Pipe Operator? The pipe operator is a special operational function available under the magrittr and dplyr package (basically developed under magrittr), which allows us to pass the result of one function/argument to the other one in sequence. It is generally denoted by symbol %>% in R Programming.


1 Answers

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)
like image 104
John Paul Avatar answered Oct 02 '22 18:10

John Paul