Search code examples
rarraysdataframecontingency

Contingency table from a 2x3 dataframe in r


I have this df

Genero   Frustrado  No frustrado
<chr>      <int>        <int>
Hombre      138           9 
Mujer       145          12 

And I need to turn it into a contingency table like this:


                Frustrado  
Genero       Si          No
    
Hombre      138           9 
Mujer       145          12 


How can I do it with a simple code chunk? (I need to replicate this many times and I would prefer not to write vectors every time)

Thanks!


Solution

  • Maybe you can try the code below

    `dimnames<-`(
      as.table(as.matrix(df[-1])),
      list(Genero = df$Genero, Frustrado = c("si", "No"))
    )
    

    which gives

            Frustrado
    Genero    si  No
      Hombre 138   9
      Mujer  145  12
    

    Data

    > dput(df)
    structure(list(Genero = c("Hombre", "Mujer"), Frustrado = c(138L,
    145L), `No frustrado` = c(9L, 12L)), class = "data.frame", row.names = c(NA,
    -2L))