Ale Rey
Ale Rey

Reputation: 85

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!

Upvotes: 1

Views: 305

Answers (2)

akrun
akrun

Reputation: 887058

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

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

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

Upvotes: 2

Related Questions