1

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!

Ale Rey
  • 75
  • 8

2 Answers2

3

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))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • I'm sorry @Thomas but I don't quite understand the first part of the code `dimnames<-`. I ran it and it throws this error "Error in df$Genero : object of type 'closure' is not subsettable" – Ale Rey Oct 05 '20 at 20:58
  • 1
    @AleRey that's because Thomas is very reasonably assuming your tibble is called `df`.Change `df` in this code to the name of your data frame and it should work – Allan Cameron Oct 05 '20 at 21:01
  • 1
    @AleRey `dimnames<-` assigns names to dimensions of table. I guess you got that error since you have factors in your `df`. Try `df <- type.convert(df,as.is = TRUE)` first and then ran the code above. – ThomasIsCoding Oct 05 '20 at 21:02
  • Thanks @AllanCameron, but I had done it an that was the output anyway. `dimnames<-`( as.table(as.matrix(tabla_genero_pivot[-1])), list(Genero = tabla_genero_pivot$Genero, Frustrado = c("si", "No")) ) – Ale Rey Oct 05 '20 at 21:03
  • @Thomas that was all about! I did what you said and works perfectly! Cheers! – Ale Rey Oct 05 '20 at 21:10
  • @AllanCameron, the error that throwed after I changed the df (the first time I had forgotten) was actually this one: Error in dimnames(as.table(as.matrix(frustracion_genero_pivot[-1])), list(Genero = frustracion_genero_pivot$Genero, : 2 arguments passed to 'dimnames' which requires 1 – Ale Rey Oct 05 '20 at 21:13
2

We can use column_to_rownames

library(tibble)
out <- df %>%
          column_to_rownames('Genero') %>%
          as.matrix

names(dimnames(out)) <- names(df)[1:2]

data

df <- structure(list(Genero = c("Hombre", "Mujer"), Frustrado = c(138L,
145L), `No frustrado` = c(9L, 12L)), class = "data.frame", row.names = c(NA,
-2L))
akrun
  • 874,273
  • 37
  • 540
  • 662