我有這個資料集和資料框矩陣串列,如下所示:
set.seed(222)
df = data.frame(x = trunc(runif(10,0,2)),
y = trunc(runif(10,4,6)),
z = trunc(runif(10,19,21)),
m = trunc(runif(10,28,30)))
df
t1 = table(df$x,df$y)
t2=table(df$z,df$m)
L = list(t1,t2)
L1 <- lapply(L, as.data.frame.matrix)
輸出是
[[1]]
4 5
0 4 2
1 3 1
[[2]]
28 29
19 3 2
20 1 4
我希望為第一個元素創建比例表:
[[1]]
4 5
0 4/(4 2) 2/(4 2)
1 3/(3 1) 1/(3 1)
謝謝
uj5u.com熱心網友回復:
我們可以sapply用來迭代 中的元素L1,獲取rowSums和獲取比例。
sapply(L1, function(x) {
tmp <- x[1, ]
tmp <- tmp/rowSums(tmp)
tmp
})
[,1] [,2]
4 0.6666667 0.6
5 0.3333333 0.4
uj5u.com熱心網友回復:
我們可能會使用proportions
sapply(L1, \(x) proportions(as.matrix(x), 1)[1,])
[,1] [,2]
4 0.6666667 0.6
5 0.3333333 0.4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529084.html
標籤:r数据框数据表排比例
