你能告诉我如何在three dimensional表格中获得百分比吗?我知道如何two dimensional通过runnin在表中创建百分比
p <-with(mtcars,tapply(carb,list(cyl,vs),length))
prop.table(p,2) # by column
Run Code Online (Sandbox Code Playgroud)
但是,如果我可以尝试添加另一个变量,我该怎么办?
p <- with(mtcars,tapply(carb,list(cyl,vs,gear),length))
Run Code Online (Sandbox Code Playgroud)
the*_*ail 16
您可以为prop.table函数指定多个级别的输入,其中1 = row,2 = column,3 = strata等
简单的例子:
test <- 1:8
dim(test) <- c(2,2,2)
test
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 5 7
[2,] 6 8
Run Code Online (Sandbox Code Playgroud)
然后你可以做以下事情:
# % of all values in each stratum/sub-table
prop.table(test,3)
# row % within each stratum/sub-table
prop.table(test,c(3,1))
# column % within each stratum/sub-table
prop.table(test,c(3,2))
Run Code Online (Sandbox Code Playgroud)
可能有一种简单的方法来处理NAs,但是一个环形交叉版本将它们设置为0's然后重置为NA's:
# set one of the values to NA as an example
test[7] <- NA
# do the procedure
nas <- is.na(test)
test[nas] <- 0
result <- prop.table(test,c(3,2))
result[nas] <- NA
result
, , 1
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
, , 2
[,1] [,2]
[1,] 0.4545455 NA
[2,] 0.5454545 1
Run Code Online (Sandbox Code Playgroud)