2

I have a dataset which has multiple columns and multiple values for each column. What I want is to have the count of each value from each column grouped by a groupID

Example

 GroupId | C1            |    C2
      1  | "valColOne1"  | "valColTwo2"
      2  |  "valColOne1" | "valColTwo2"
      2  |  "valColOne1" | "valColTwo2"
      2  |  "valColOne2" | "valColTwo1"
      1  |  "valColOne1" | "valColTwo1"

And the result should be

    GroupId | valColOne1 | valColOne2 | valColTwo1 | valColTwo2
         1  |    2       |     0      |    1       |  1
         2  |    2       |     1      |    1       |  2

To mention that all values in the intial table will be strings.

3
  • 1
    using dplyr/tidyr, group_by, do(table), spread might do.
    – Khashaa
    Mar 30, 2015 at 15:19
  • @Khashaa thanks. Can you expand a little on that. Im not a real expert on R so any further explanation would be helpful.
    – coredump
    Mar 30, 2015 at 15:24
  • You already have a couple of nice answers:)
    – Khashaa
    Mar 30, 2015 at 15:29

2 Answers 2

4

Take your original data frame (which I've called dat) and melt it into long format. Then use dcast to count the number of occurrences of each value.

library(reshape2)

dat.m = melt(dat, id.var="GroupId")

dcast(dat.m, GroupId ~ value)

  GroupId   valColOne1    valColOne2   valColTwo1  valColTwo2
1       1             2             0           1           1
2       2             2             1           1           2

It's easiest to see what each function does if you run them and look at the intermediate results. For some examples, see here and here.

2
  • Great! Can you explain what each function does ? never used reshape before.
    – coredump
    Mar 30, 2015 at 15:27
  • Also really nice package. wouldn't thought there would be such a easy way to do this :)
    – coredump
    Mar 30, 2015 at 15:32
2

You could use table from base R

table(data.frame(GroupId= df1$GroupId, Val=unlist(df1[-1])))
#         Val
# GroupId valColOne1 valColOne2 valColTwo1 valColTwo2
#  1          2          0          1          1
#  2          2          1          1          2

data

df1 <- structure(list(GroupId = c(1, 2, 2, 2, 1), C1 = c("valColOne1", 
"valColOne1", "valColOne1", "valColOne2", "valColOne1"), 
C2 =   c("valColTwo2", 
"valColTwo2", "valColTwo2", "valColTwo1", "valColTwo1")),
.Names =  c("GroupId", 
"C1", "C2"), row.names = c(NA, -5L), class = "data.frame")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.