Ray Gold
Ray Gold

Reputation: 168

How to make multiple layered table form with R and shiny?

Any one can help me create table like this (multiple layers)?

I have tried many different functions in R such as table, tapply, aggregate etc. I can make the parts of the values, but do not know how to add the parts of the column and row names (gray part) ..

Suppose there are four variables : gender, grade, year, area. With 4 factorial input variables, I would like to create this form of table with R and shiny. The values in the table are just counts.

Any help will be appreciated.

enter image description here

Upvotes: 4

Views: 2509

Answers (1)

smillig
smillig

Reputation: 5351

I think the ftable() function is what you're looking for:

d <- data.frame(Year=sample(c("2007", "2014"), 775, replace=TRUE),
     Gender=sample(c("Mail", "Femail"), 775, replace=TRUE),
     Grade=sample(c("1st grad", "2nd grad", "3rd grad"), 775, replace=TRUE),
     Area=sample(c("City area", "Rural area"), 775, replace=TRUE),
     Income=1000*runif(775))

d1 <- ftable(d, row.vars=c("Year", "Area"), col.vars=c("Gender", "Grade"))
d1

#                 Gender   Femail                       Mail                  
#                 Grade  1st grad 2nd grad 3rd grad 1st grad 2nd grad 3rd grad
# Year Area                                                                   
# 2007 City area               27       32       37       37       30       37
#      Rural area              29       26       25       41       36       30
# 2014 City area               30       29       30       27       32       29
#      Rural area              35       36       42       31       35       32

If you want to display the mean income for each of the groups in the table, there are a number of options. One way is to use a combination of functions from the plyr and reshape2 packages. There are probably better or more efficient ways, but this does the trick:

library(plyr)
d1 <- ddply(d, .(Year, Gender, Grade, Area), summarise,
      mean=mean(Income))

library(reshape2)
dcast(d1, Year+Area ~ Gender+Grade)

Upvotes: 2

Related Questions