Here is some data:
dta <- data.frame(
id = 1:10,
code1 = as.factor(sample(c("male", "female"), 10, replace = TRUE)),
code2 = as.factor(sample(c("yes", "no", "maybe"), 10, replace = TRUE)),
code3 = as.factor(sample(c("yes", "no"), 10, replace = TRUE))
)
I would like a nicely formatted frequency table for the code variables.
codes <- c("code1", "code2", "code3")
For example, we can run the build-in command table
.
> sapply(dta[, codes], table)
$code1
female male
4 6
$code2
maybe no yes
5 2 3
$code3
no yes
4 6
All the information is here, but what would be nice is to have a table thusly:
library(plyr)
ddply(dta, .(code1), summarize, n1 = length(code1))
code1 n1
1 female 4
2 male 6
And this three times. Can be separate dataframes or all in one.
How can we loop over the variables? Or any other approaches.