views:

267

answers:

3

In R (or S-PLUS), what is a good way to aggregate String data in a data frame?

Consider the following:

myList <- as.data.frame(c("Bob", "Mary", "Bob", "Bob", "Joe"))

I would like the output to be:

 [Bob,  3
  Mary, 1
  Joe,  1]

Currently, the only way I know how to do this is with the summary function.

> summary(as.data.frame(myList))

 Bob :3                                
 Joe :1                                
 Mary:1

This feels like a hack. Can anyone suggest a better way?

+1  A: 

Do you mean like this?

> myList <- c("Bob", "Mary", "Bob", "Bob", "Joe")
> r <- rle(sort(myList))
> result <- as.data.frame(cbind(r$values, r$lengths))
> names(result) <- c("Name", "Occurrences")
> result
  Name Occurrences
1  Bob           3
2  Joe           1
3 Mary           1
Jouni K. Seppänen
+2  A: 

Using table, no need to sort:

ctable <- table(myList);
counts <- data.frame(Name = names(ctable),Count = as.vector(ctable));
bubaker
you can simplify the last line to as.data.frame(ctable)Note that the semicolons are only needed if you put more than one command on a line.
Thierry
+2  A: 

This is a combination of the above answers (as suggested by Thierry)

data.frame(table(myList[,1]))

which gives you

  Var1 Freq
1  Bob    3
2  Joe    1
3 Mary    1
andrewj
It gives an error for me - a one liner based on Thierry's suggestion would be: as.data.frame(table(myList))
bubaker
That's interesting. What kind of error message did you get? I just tried it without getting an error message.
andrewj
Scratch that - I tried it after defining myList as a list, not a data.frame
bubaker