![](/img/trans.png)
[英]How to calculate the sum of periods over each column for each row and divide it by a total minimum value in R
[英]R: how to divide each cell value (dataframe) by a quantity that includes the correspoding row AND column total
我有一個交叉表(數據框格式),從中我計算了 chi-sq 標准化殘差。 下面我提供了兩個可重現的數據集。
交叉表:
df <- structure(c(310, 36, 0, 0, 212, 158, 9, 0, 21, 35, 17, 4, 25,
102, 49, 18, 7, 35, 51, 28), .Dim = 4:5, .Dimnames = list(c("none",
"grade1", "grade2", "grade3"), c("0-9", "10-19", "20-29", "30-39",
"40+")))
標准化殘差
st.residuals <- structure(c(9.882, -7.267, -6.247, -3.935, 1.21, 3.035, -5.162,
-4.119, -2.96, 1.945, 2.821, 0.298, -7.492, 4.82, 5.796, 3.161,
-7.005, -0.738, 10.11, 9.704), .Dim = 4:5, .Dimnames = list(c("none",
"grade1", "grade2", "grade3"), c("0-9", "10-19", "20-29", "30-39",
"40+")))
目標
我要計算調整后的標准化殘差,這需要將每個標准化殘差除以下圖中指示的數量,其中 GT 是表格總計,CT 是列總計,RC 是行總計:
我被困在哪里
我很難弄清楚(我的錯)如何在 R 中實現分母的計算。 特別是,我不知道如何編碼,以便對於每個單元格 R 將考慮相應的行和列總數。
1) R 已經在 chisq.test 中有這個:
chisq.test(df)$stdres
2)或以下。 殘差與問題中的 st.residuals 相同,最后一行產生與上述行相同的結果。
expected <- outer(rowSums(df), colSums(df)) / sum(df)
residuals <- (df - expected) / sqrt(expected)
residuals / sqrt(outer((1 - rowSums(df) / sum(df)), (1 - colSums(df) / sum(df))))
3)或者我們可以使用掃描來計算上面的(1)。 殘差來自(2),並且如前所述,等於問題中的 st.residuals 。
residuals |>
sweep(1, sqrt(1 - rowSums(df) / sum(df)), `/`) |>
sweep(2, sqrt(1 - colSums(df) / sum(df)), `/`)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.