Question:
Suppose I have the following data
tabela<-structure(list(nome = structure(c(2L, 9L, 6L, 1L, 8L, 3L, 4L,
5L, 7L, 10L, 11L), .Label = c("12 Anos de Escravidão", "A Caça",
"Ela", "Gravidade", "O Hobbit: A Desolação de Smaug", "O Lobo de Wall Street",
"Os Suspeitos", "Rush: No Limite da Emoção", "The Avengers - Os Vingadores",
"The Grand Budapest Hotel", "Uma Aventura LEGO"), class = "factor"),
ano = c(2012L, 2012L, 2013L, 2013L, 2013L, 2013L, 2013L,
2013L, 2013L, 2014L, 2014L)), .Names = c("nome", "ano"), row.names = 240:250, class = "data.frame")
How do I collapse the "name" text column so that my data frame looks like this:
ano quantidade nomes
2012 2 A Caça, The Avengers - Os Vingadores
2013 7 O Lobo de Wall Street, 12 Anos de Escravidão, Rush: No Limite da Emoção, Ela, Gravidade, O Hobbit: A Desolação de Smaug, Os Suspeitos
2014 2 The Grand Budapest Hotel, Uma Aventura LEGO
Answer:
You can do it with dplyr
using the paste
option collapse
:
library(dplyr)
tabela2<-tabela %>% group_by(ano) %>% summarise(quantidade = n(),
nomes = paste(nome,collapse=", "))
Out of curiosity I'll also put plyr
(but dplyr
is faster).
library(plyr)
tabela2<- ddply(tabela, .(ano), summarise, quantidade=length(nome), nomes=paste(nome, collapse=","))