Search code examples
rloopscalculationsurvey

Calculation of number and percentage of right answers for each participant in R


I have a table of survey with answers that might be "right" or "wrong":

Participant Answer 1 Answer 2 Answer 3 ... Answer n
1 Right Wrong Wrong ... Right
2 Right Wrong Right .... Right
3 Wrong Right Right ... Wrong

I want to calculate the number and percentage of "right" questions for every participant and make result that will look like this:

Participant Number of right answers Percentage of right answers
1 p1 p1, %
2 p2 p2, %
3 p3 p3, %
... ... ....
n pn pn, %

I think it is possible to do through loop, however, I don' know how to do this.


Solution

  • You can use rowSums and rowMeans from base R. Since you don't provide a reproducible example, I created one, with 10 questions and participants:

    df <- data.frame(participant = 1:10, 
               as.data.frame(matrix(sample(c("Right", "Wrong"), 100, replace = TRUE), nrow = 10)))
    
    #    participant    V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
    # 1            1 Right Right Right Wrong Wrong Right Wrong Wrong Wrong Right
    # 2            2 Wrong Right Right Right Wrong Right Wrong Wrong Right Right
    # 3            3 Right Right Wrong Right Right Wrong Right Wrong Right Right
    # 4            4 Right Wrong Right Right Right Right Right Right Wrong Wrong
    # 5            5 Right Right Right Wrong Right Right Wrong Right Wrong Wrong
    # 6            6 Wrong Wrong Right Wrong Wrong Wrong Wrong Wrong Wrong Right
    # 7            7 Wrong Right Wrong Wrong Right Right Wrong Wrong Wrong Wrong
    # 8            8 Right Wrong Wrong Right Right Wrong Wrong Right Right Wrong
    # 9            9 Right Wrong Wrong Right Right Right Wrong Wrong Right Right
    # 10          10 Wrong Wrong Wrong Wrong Wrong Wrong Right Wrong Wrong Right
    
    data.frame(df[1],
               right_answers = rowSums(df[-1] == "Right"),
               p_right_answers = rowMeans(df[-1] == "Right"))
    
    #    participant right_answers p_right_answers
    # 1            1             5             0.5
    # 2            2             6             0.6
    # 3            3             7             0.7
    # 4            4             7             0.7
    # 5            5             6             0.6
    # 6            6             2             0.2
    # 7            7             3             0.3
    # 8            8             5             0.5
    # 9            9             6             0.6
    # 10          10             2             0.2