在R 3.4.0中,如何将prop.table()生成的所有百分比舍入到一行中的3个小数位?
这不起作用:
MyTable$MyCol %>% table() %>% prop.table()*100 %>% round(.,3)
-7 -2 0 1 2 3 4 5
0.4672897 0.2336449 31.7757009 1.6355140 44.3925234 20.3271028 0.4672897 0.7009346
期待类似:
-7 -2 0 1 2 3 4 5
0.467 0.233 31.775 1.635 44.392 20.327 0.467 0.700
答案 0 :(得分:3)
您需要将乘法分成单独的操作:
mtcars$cyl %>% table() %>% prop.table() %>% `*`(100) %>% round(2)
答案 1 :(得分:2)
我们还可以使用{}
在...
内评估(%>% ... %>%
)整体,然后切换到下一个%>%
mtcars$cyl %>%
table() %>%
prop.table() %>% {. * 100} %>%
round(2)
.
# 4 6 8
# 34.38 21.88 43.75
答案 2 :(得分:1)
初始化数据
a <- c(0.4, 0.2336449, 31.7757009, 1.6355140, 44.3925234, 20.3271028, 0.4672897, 0.7)
第一种方式
format(round(a, 3), nsmall = 3)
# [1] " 0.400" " 0.234" "31.776" " 1.636" "44.393" "20.327" " 0.467" " 0.700"
第二种方式
options(digits=3)
a
# [1] 0.400 0.234 31.776 1.636 44.393 20.327 0.467 0.700
答案 3 :(得分:0)
在R 3.5.1中,以下对我有用:
data=sample(1:5, 100, replace=T)
round(prop.table(table(data)),3)
#data
# 1 2 3 4 5
#0.16 0.24 0.16 0.18 0.26
除非我缺少任何东西,否则似乎或多或少都可以满足您的要求。