user11740857
user11740857

Reputation: 480

cast for all the columns in a dataframe

Is there way to cast all columns in a dataframe

Example

df
ColA   ColB
0       1
0       1
1       1
1       0

Can we populate number of Zeros here

expected output

df
New_col    0    1 
ColA       2    2
ColB       1    3

Upvotes: 0

Views: 56

Answers (3)

Waldi
Waldi

Reputation: 41220

With data.table:

df <- read.table(text = "
ColA   ColB
0       1
0       1
1       1
1       0",header=T)

library(data.table)
setDT(df)

dcast(melt(df,variable.name = 'NewCol',measure.vars = 1:2), 
      fun.aggregate = length, 
      formula = NewCol ~ value)

#>    NewCol 0 1
#> 1:   ColA 2 2
#> 2:   ColB 1 3

Upvotes: 1

Karthik S
Karthik S

Reputation: 11584

Does this work:

library(dplyr)
library(tidyr)
df %>% pivot_longer(cols = everything(), names_to = 'New_Col') %>% 
count(New_Col,value) %>% 
pivot_wider(id_cols = New_Col, names_from = value, values_from = n)
# A tibble: 2 x 3
  New_Col   `0`   `1`
  <chr>   <int> <int>
1 ColA        2     2
2 ColB        1     3

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101753

You can try stack + table

> t(table(stack(df)))
      values
ind    0 1
  ColA 2 2
  ColB 1 3

or

> as.data.frame.matrix(t(table(stack(df))))
     0 1
ColA 2 2
ColB 1 3

Upvotes: 3

Related Questions