Frage

So I have a data frame that looks like this:

   Animal    Food   LikeScore   
1   cat      fish      98
2   cat      milk      72
3   cat     shrimp     88
4   dog     steak      99
5   dog      poo       55

I would like to generate a data frame that combines animals into one row, with a list of all the foods they like into another column on the same row (regardless of the score):

    Animal          Food
1    cat      fish, milk, shrimp
2    dog      steak, poo

Is there a function in R that can do this? Thanks!

War es hilfreich?

Lösung

I like to use plyr for this:

library(plyr)
ddply(df, .(Animal), summarize, Food = paste(Food, collapse = ', '))

Note that the code is untested because your example is not reproducible. However, an example using mtcars shows that it works:

ddply(mtcars, .(gear), summarize, carb = paste(carb, collapse = ', '))
  gear                                        carb
1    3 1, 2, 1, 4, 3, 3, 3, 4, 4, 4, 1, 2, 2, 4, 2
2    4          4, 4, 1, 2, 2, 4, 4, 1, 2, 1, 1, 2
3    5                               2, 2, 4, 6, 8
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top