Dieu94
Dieu94

Reputation: 455

How to summarize values across multiple columns?

I have a dataframe that looks like this:

1  2  3  4  5

A  B  A  B  A

C  B  B  B  B 

A  C  A  B  B

And I would like to summarize my data in a frequency table like this:

   A  B  C
1  2  0  1
2  0  2  1
3  2  1  0
4  0  3  0
5  1  2  0

How would I be able to do this?

Upvotes: 3

Views: 52

Answers (4)

akrun
akrun

Reputation: 887028

An option with base R with table

table(c(col(df1)),  c(t(df1)))
   
    A B C
  1 2 1 0
  2 1 1 1
  3 0 3 0
  4 1 1 1
  5 1 2 0

Data

df1 <- structure(list(`1` = c("A", "C", "A"), `2` = c("B", "B", "C"), 
    `3` = c("A", "B", "A"), `4` = c("B", "B", "B"), `5` = c("A", 
    "B", "B")), class = "data.frame", row.names = c(NA, -3L))

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101189

Another table option with stack

> t(table(stack(df)))
   values
ind A B C
  1 2 0 1
  2 0 2 1
  3 2 1 0
  4 0 3 0
  5 1 2 0

Upvotes: 2

Martin Gal
Martin Gal

Reputation: 16978

You could use

library(tidyr)

data %>% 
  pivot_longer(everything()) %>% 
  { table(.$name, .$value) }

which returns

    A B C
  1 2 0 1
  2 0 2 1
  3 2 1 0
  4 0 3 0
  5 1 2 0

Upvotes: 3

Anoushiravan R
Anoushiravan R

Reputation: 21908

You can use the following solution:

library(tidyr)
library(janitor)

tab %>%
  pivot_longer(everything(), names_to = "nm", values_to = "val", 
               names_prefix = "X") %>%
  tabyl(nm, val)

 nm A B C
  1 2 0 1
  2 0 2 1
  3 2 1 0
  4 0 3 0
  5 1 2 0

Upvotes: 3

Related Questions