Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

r - How to create a prop.table() for a three dimension table?

Could you let know how I can get percentages in a three dimensional table. I know how to create percentages in a two dimensional table by runnin the following

p <-with(mtcars,tapply(carb,list(cyl,vs),length))
prop.table(p,2) # by column

However, if I can try to add another variable, I dont how to do?

p <- with(mtcars,tapply(carb,list(cyl,vs,gear),length))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can specify multiple levels of input to the prop.table function, where 1=row, 2=column, 3=strata etc etc

Simple example:

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

Then you can do things like:

# % 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))

There might be a simple way to deal with NAs, but a roundabout version would be to set them as 0's and then reset as 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...