在R中制作表格的传统方式:
data(mtcars)
round(100*prop.table(xtabs(~ gear + cyl, data = mtcars), 1), 2)
Run Code Online (Sandbox Code Playgroud)
回报
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
Run Code Online (Sandbox Code Playgroud)
为了使用magrittr管道复制这个,我尝试过:
library(magrittr)
mtcars %>%
xtabs(~ gear + cyl, data = .) %>%
prop.table(., 1)
Run Code Online (Sandbox Code Playgroud)
到目前为止,它很有效
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
Run Code Online (Sandbox Code Playgroud)
但任何尝试执行下一部分,其中我将比例转换为百分比,然后舍入,会导致错误.例如:
mtcars %>%
xtabs(~ gear + cyl, data = .) %>%
100*prop.table(., 1)
Run Code Online (Sandbox Code Playgroud)
和
mtcars %>%
xtabs(~ gear + cyl, data = .) %>%
prop.table(., 1) %>%
100 * .
Run Code Online (Sandbox Code Playgroud)
都会导致错误.我错过了什么?
Joh*_*aul 21
你需要*输入引号 - "*"()也可以1用作你的参数prop.table来匹配这个例子.
mtcars %>%
xtabs(~ gear + cyl, data = .) %>%
prop.table(., 1) %>%
"*"(100 ) %>% round(.,2)
Run Code Online (Sandbox Code Playgroud)