1

I have a dataset like this below

Col  Value
  A      1
  A      0
  A      1
  A      1
  A      1
  B      0
  B      1
  B      0
  B      1
  B      1

How do I transform this so that it looks like this below

Col1  Col2  Col3
   A     4     1
   B     3     2

Col2 counts all the 1s and Col3 counts all the 0s for each factor value in Col1.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

2

For this, you can just use table:

table(mydf)
##    Value
## Col 0 1
##   A 1 4
##   B 2 3

Or:

library(data.table)
as.data.table(mydf)[, as.list(table(Value)), by = Col]
##    Col 0 1
## 1:   A 1 4
## 2:   B 2 3
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
2

Or we can use dcast

library(reshape2)
dcast(df1, Col~Value, value.var='Value', length)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Another approach of aggregating the values is:

df <- data.frame(Col=c("A","A","A","A","A","B","B","B","B","B"), Value=c(1,0,1,1,1,0,1,0,1,1))

new_df <- as.data.frame(with(df, tapply(Value, list(Col, Value), FUN = function(x) length(x))))

new_df <- setNames(cbind(rownames(new_df), new_df), c("Col1","Col2","Col3"))

new_df 

     Col1 Col2 Col3
 A    A    1    4
 B    B    2    3

We can set rownames to NULL if do not wish to see them:

rownames(new_df) <- NULL

Result:

   Col1 Col2 Col3
1    A    1    4
2    B    2    3
ruchijain90
  • 181
  • 6