Ale Rey
Ale Rey

Reputation: 85

Pivot a data frame and count categorical observations at the same time in r

I've been struggling with this. This is an abbreviation of my df:

structure(list(`Loperamida en diarrea` = c("Muy efectiva", "Muy efectiva", 
"Muy efectiva", "Algo efectiva"), `Carbón en diarrea` = c("Algo efectiva", 
"Algo efectiva", "Algo efectiva", "No Se"), `Bismuto en diarrea` = c("Algo efectiva", 
"Muy efectiva", "Algo efectiva", "No Se"), `Rifaximina en diarrea` = c("Algo efectiva", 
"Algo efectiva", "Algo efectiva", "Algo efectiva"), `Otros antibióticos en diarrea` = c("Algo efectiva", 
"Muy efectiva", "Algo efectiva", "Algo efectiva"), `Probióticos en diarrea` = c("Algo efectiva", 
"Algo efectiva", "Algo efectiva", "Algo efectiva"), `Trimebutina en diarrea` = c("Algo efectiva", 
"Algo efectiva", "Algo efectiva", "Algo efectiva")), row.names = c(NA, 
4L), class = "data.frame")

That looks like this in an even shorter version:

    
   Loperamida en diarrea   Carbón en diarrea     Bismuto en diarrea
     <chr>                       <chr>                 <chr>
1   Muy efectiva             Algo efectiva         Algo efectiva    
2   Muy efectiva             Poco efectiva          Muy efectiva    
3   Muy efectiva             Algo efectiva         Poco efectiva    
4   Algo efectiva                No Se                 No Se

And I need to transform it in a table where the columns are the 4 different categorical of observations, the rows are the variables (the column names) and the values are the number of observations for each kind (n). Like this:

                            Muy efectiva  Algo efectiva    Poco efectiva  No Se
                                <int>         <int>           <int>       <int>
Loperamida en diarrea             n             n               n           n
Carbón en diarrea                 n             n               n           n
Bismuto en diarrea                n             n               n           n

Upvotes: 0

Views: 167

Answers (2)

Ale Rey
Ale Rey

Reputation: 85

After some trying I have found another solution that might be useful:

cols <- c("Loperamida en diarrea","Carbón en diarrea","Bismuto en diarrea")

mtabulate(df[cols])

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388907

Using dplyr and tidyr you can do :

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = everything()) %>%
  count(name, value) %>%
  pivot_wider(names_from = value, values_from = n, values_fill = 0)

Upvotes: 1

Related Questions