How to make two loops for the same code only go varying the columns of the courses and the columns of the questions?

-1

I have a date.frame with many codes in the rows and many columns of questions, I'm making the simple frequency of each question would like to know how to vary the courses and questions at once, without having to manually repeat the code I generated a thousand times?

cursos <- c(rep(12671,10)) 
pergunta1 <- c(1,2,3,4,5,6,7,7,2,1)
pergunta2 <- c(1,1,2,1,3,4,2,1,3,3)
df <- data.frame(cursos,pergunta1,pergunta2)
    
asked by anonymous 09.06.2018 / 17:14

1 answer

2

I think a better way than using loops is to use packages like dplyr and reshape :

library(dplyr)
library(reshape2)

df %>%
  melt(id="cursos") %>%
  dcast(value ~ variable + cursos, fun.aggregate=length)

  value pergunta1_12671 pergunta2_12671
1     1               2               4
2     2               2               2
3     3               1               3
4     4               1               1
5     5               1               0
6     6               1               0
7     7               2               0

The melt function transforms the data into a long format, leaving everything in three columns: the first for courses, the second for questions and the last for counting these questions.

I then used the dcast function, along with the fun.aggregate=length option, to count the number of times each question appears.

    
09.06.2018 / 22:59