我有這張桌子:
| 團體 | 1990 年 5 月 | 1990 年 6 月 | 1990 年 7 月 |
|---|---|---|---|
| 1 | 581 | 552 | 465 |
| 2 | 193 | 184 | 176 |
| 3 | 207 | 177 | 165 |
| 全部的 | 981 | 913 | 806 |
我想從行總數計算行級別的百分比。
| 團體 | 1990 年 5 月 | 1990 年 6 月 | 1990 年 7 月 |
|---|---|---|---|
| 1 | 0.59 | 0.60 | 0.58 |
| 2 | 0.19 | 0.21 | 0.22 |
| 3 | 0.21 | 0.19 | 0.20 |
| 全部的 | 1 | 1 | 1 |
我現在已經到了這一步,但這不是我想要的。
df <- data.frame(group=c('1','2','3','Total'),may_1990=c(581,193,207,981),jun_1990=c(552,184,177,913),jul_1990=c(465,176,165,806))
total <- df %>% slice_tail(n = 1)
z <- df %>% rowwise() %>% mutate(across(where(is.numeric), ~ .x/total[-1]))
uj5u.com熱心網友回復:
與across:
library(dplyr)
df %>%
mutate(across(where(is.numeric), ~ .x / .x[group == "Total"]))
group may_1990 jun_1990 jul_1990
1 1 0.5922528 0.6046002 0.5769231
2 2 0.1967380 0.2015334 0.2183623
3 3 0.2110092 0.1938664 0.2047146
4 Total 1.0000000 1.0000000 1.0000000
根據您資料的性質,如果您更喜歡基本 R,這也可以作業:
df[-1] <- sapply(df[-1], proportions) * 2
uj5u.com熱心網友回復:
我認為實作這種表的簡單方法是使用 table() 函式:
df <- data.frame(group=c('1','2','3','Total'),may_1990=c(581,193,207,981),jun_1990=c(552,184,177,913),jul_1990=c(465,176,165,806))
# Compute proportions for the central data
prop = proportions(as.matrix(df[-4,-1]), 2)
# Add total at the column level (margin = 1)
prop = addmargins(prop, 1)
# Create the final table
df_end = data.frame(
group=c('1','2','3','Total'),
prop
)
你得到這個:
group may_1990 jun_1990 jul_1990
1 1 0.5922528 0.6046002 0.5769231
2 2 0.1967380 0.2015334 0.2183623
3 3 0.2110092 0.1938664 0.2047146
Sum Total 1.0000000 1.0000000 1.0000000
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/529915.html
標籤:rdplyr
下一篇:有沒有辦法使以下演算法更有效?
