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?
%>% 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).
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 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 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With