如果我有一張這樣的桌子,
| 分配 | 顏色 |
|---|---|
| 一種 | 紅色的 |
| 一種 | 藍色 |
| 一種 | 藍色 |
| 一種 | 黃色的 |
| 乙 | 藍色 |
| 乙 | 黃色的 |
| C | 綠色的 |
我想根據每個部門找到顏色的百分比,所以輸出應該是這樣的,
| 分配 | 紅色的 | 藍色 | 黃色的 | 綠色的 |
|---|---|---|---|---|
| 一種 | 25.0 | 50.0 | 25.0 | 0 |
| 乙 | 0 | 50.0 | 50.0 | 0 |
| C | 0 | 0 | 0 | 100.0 |
我怎樣才能在 R 中做到這一點?
uj5u.com熱心網友回復:
你可以做
tab <- table(df$Division, df$Color)
100 * tab / rowSums(tab)
#> Blue Green Red Yellow
#> A 50 0 25 25
#> B 50 0 0 50
#> C 0 100 0 0
可重現格式的資料
df <- structure(list(Division = c("A", "A", "A", "A", "B", "B", "C"
), Color = c("Red", "Blue", "Blue", "Yellow", "Blue", "Yellow",
"Green")), class = "data.frame", row.names = c(NA, -7L))
uj5u.com熱心網友回復:
這可能是另一種使用方法janitor,并且很高興了解:
library(janitor)
df %>%
tabyl(Division, Color) %>%
adorn_percentages() %>%
adorn_pct_formatting()
Division Blue Green Red Yellow
A 50.0% 0.0% 25.0% 25.0%
B 50.0% 0.0% 0.0% 50.0%
C 0.0% 100.0% 0.0% 0.0%
uj5u.com熱心網友回復:
使用proportions.
proportions(table(df), margin=1)*100
# Color
# Division Blue Green Red Yellow
# A 50 0 25 25
# B 50 0 0 50
# C 0 100 0 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449407.html
標籤:r
上一篇:基于邏輯列更寬地旋轉數值列
