0

I am attempting to make a nested table using the tables package in r that can then be added into a knitr document.

I would like to make a table where each row is a different categorical variable in the data set and each column is the frequency and percent of each response option.

I would like the result to look something like this

Variable     1-5 times        6-10 times      11-15 times
           freq    Percent  freq   percent   freq  percent    
eating       5       33       5      33       5       33
drinking     5       33       5      33       5       33

Here is some code that should allow for the production of the above table.

eating <- c("1-5 times", "1-5 times", "1-5 times","1-5 times","1-5 times", "6-10 times","6-10 times","6-10 times","6-10 times","6-10 times", "11-15 times","11-15 times","11-15 times","11-15 times","11-15 times")
drinking<-c("1-5 times", "1-5 times", "1-5 times","1-5 times","1-5 times", "6-10 times","6-10 times","6-10 times","6-10 times","6-10 times", "11-15 times","11-15 times","11-15 times","11-15 times","11-15 times")
eating<-factor(eating)
drinking<-factor(drinking)
df<-data.frame(eating,drinking)

Does anyone know a way of doing this? Either with the tables package or something else?

user2460499
  • 151
  • 2
  • 3
  • 7

1 Answers1

0

This is not exactly what you are asking for but close enough:

library(plyr)
x<-ddply(df,.(eating,drinking),summarize,freq=length(eating))
x$perc<-with(x,(100*freq/sum(freq)))

   > x
       eating    drinking freq     perc
1   1-5 times   1-5 times    5 33.33333
2 11-15 times 11-15 times    5 33.33333
3  6-10 times  6-10 times    5 33.33333
Metrics
  • 15,172
  • 7
  • 54
  • 83