R - find and calculate with unique combinations of values

Posted by lecodesportif on Stack Overflow See other posts from Stack Overflow or by lecodesportif
Published on 2011-01-14T23:47:38Z Indexed on 2011/01/15 1:53 UTC
Read the original article Hit count: 457

Filed under:
|
|

I would like to work with unique combinations of var1 and var2.

foo <- data.frame(var1= c(1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4), var2=c(1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 3, 3))

As has been noted (+1 for answers), unique(foo) results in this:

      var1  var2
 1    1     1
 2    2     1
 3    2     2
 4    3     1
 5    3     2
 6    4     2
 7    4     3

Based on the unique combinations, how do I get the number of occurrences of a var1 value and the sum (bla) of each var1 value's var2 values. The output could look like this:

      var1  n    bla
1     1     1    1
2     2     2    3
3     3     2    3
4     4     2    5

edit: The question was too basic and probably duplicate so I extended it.

© Stack Overflow or respective owner

Related posts about r

    Related posts about unique