2015-01-26 112 views
4

製作表R中的一種傳統方式:如何做乘法magrittr管

data(mtcars) 

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

回報

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 

要使用magrittr管道複製這一點,我已經試過:

library(magrittr) 

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

這很好的工作到這一點

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 

但是任何嘗試執行下一部分,其中我將百分比轉換爲百分比,然後舍入,導致錯誤。例如:

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

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

都會導致錯誤。我錯過了什麼?

+3

在你的例子中,邊距是用於行,在'magrittr'中,你使用'columns'。 (。,1)%>%multiply_by(100)%>%round(。,2)' – akrun 2015-01-26 18:22:06

+1

請參閱http:// stackoverflow.com/a/27364575/3871924 – agenis 2015-01-26 18:22:24

+0

@ akrun - 感謝您的支持,上面已經更正。 – tomw 2015-01-26 18:25:53

回答

11

您需要把*放在引號中 - "*"(),也可以用1作爲參數prop.table來匹配例子。

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

太棒了,謝謝。 – tomw 2015-01-26 18:28:34