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

Asked

Viewed 60 times

-1

I have a data.frame with lots of code in the rows and lots of columns of questions, I’m doing the simple frequency of each question I would like to know how to vary the courses and questions at once, without having to repeat 1000 times manually the code I generated?

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)
  • 1

    Welcome to Stackoverflow! Unfortunately, this question cannot be reproduced by anyone trying to answer it. Please, take a look at this link and see how to ask a reproducible question in R. So, people who wish to help you will be able to do this in the best possible way.

1 answer

3

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 function melt transforms the data into long format, leaving everything in three columns: the first for the courses, the second for the questions and the last for the counting of these questions.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.