Reputation: 480
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
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
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
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