I have given the results of several surveys as data frames with the questions being the columns and the answers being the rows. That is, the data frame is of the following form:
Q1 Q2 Q3 ... Qn
1 5 4 5 ... 2
2 5 5 NA ... 3
3 2 4 1 ... 2
4 3 3 3 ... 3
5 5 3 5 ... 1
...
The number of questions (= columns) varies from survey to survey (and is usually quite large), but given the answers are always integers in the range from 1 to 5, or NA if no answer has been given.
I need to transform this data into a (long form) data frame representing the frequency count of the given answers for each question, that is:
question value freq
Q1 1 12
Q1 2 41
Q1 3 123
Q1 4 231
Q1 5 401
Q2 1 11
Q2 2 32
Q2 3 122
Q2 4 321
Q2 5 173
...
However, I was unable to come up with a solution achieving this. I understand that data.frame(table(survey$Q1))
kind of produces the frequency count I am looking for, but only for a single question. Combining all these data frames "by hand" for each of the large number of questions is infeasible. When possible, I am also looking for a rather general solution that can handle the variable number of questions in my different surveys.
Thanks in advance, any help is appreciated.
Code snippet for generating sample data:
Q1 = c(5, 5, 2, 3, 5, 4, 3, 5, 2, 3)
Q2 = c(4, 5, 4, 3, 3, 5, 3, 5, 4, 3)
Q3 = c(5, NA, 1, 3, 5, 5, 2, 3, 5, 5)
Qn = c(2, 3, 2, 3, 1, NA, 3, 2, 3, 1)
survey <- data.frame(Q1,Q2,Q3,Qn)