Home > Software engineering >  How to output a results in datafram format with a wrong/correct answers by group in R
How to output a results in datafram format with a wrong/correct answers by group in R

Time:09-15

I have a data frame with two columns. First column contains categories such as "Syestem 1", "Syestem 2", and the second column has numbers that represent the correct/wrong answers. Correct means 1, and wrong means 0.

For example:

SYSTEM Q1
S1 0
S1 1
S2 1
S2 0
S2 1

How to write R code to produce this table below

System Coorect answers Wrong answers Total answrs
S1 1 1 2
S2 2 1 3

I used group by, filter, and if condition, but it seems not to be working. Please help me address this issue in R.

CodePudding user response:

Using group_by and summarise you could do:

dat <- data.frame(
  SYSTEM = c("S1", "S1", "S2", "S2", "S2"),
  Q1 = c(0L, 1L, 1L, 0L, 1L)
)

library(dplyr)

dat |>
  group_by(SYSTEM) |>
  summarise(`Correct answers` = sum(Q1 == 1), `Wrong answers` = sum(Q1 == 0), `Total answers` = n())
#> # A tibble: 2 × 4
#>   SYSTEM `Correct answers` `Wrong answers` `Total answers`
#>   <chr>              <int>           <int>           <int>
#> 1 S1                     1               1               2
#> 2 S2                     2               1               3
  •  Tags:  
  • r
  • Related