R filter sets

2

I'm taking the first steps in programming and with the R language and I have the following doubt

I have a birthday dataframe with the following format

Months | Person

April Joao

March Ana

April Carlos

June Joan

March Pedro

and wanted an output of the genre

March - Ana, Pedro

April - Joao, Carlos

June - Joan

I'm using unique (df $ months) and I get the unique months but I can not get every month to select all the people

I was thinking of saving the indices of each unique (df $ months) and then selecting the names of these indices ... this for each unique (df $ months). But this does not seem to me to be very "right" at optimization level.

Can anyone help?

Thank you:)

    
asked by anonymous 08.01.2015 / 16:23

1 answer

1

One solution to this would be to use the aggregate function.

dados <- read.table(text='Meses Pessoa
Abril Joao
Março Ana
Abril Carlos
Junho Joana
Março Pedro', header = T)

dados_agregados <- aggregate(Pessoa ~ Meses, FUN = function(x) { paste0(x, collapse = ', ') }, data = dados)
dados_agregados

apply(dados_agregados, 1, function(x) { cat(sprintf('%s - %s\n', x[1], x[2])) })
invisible(apply(dados_agregados, 1, function(x) { cat(sprintf('%s - %s\n', x[1], x[2])) }))

Note that the second does not show NULL after the table. If you want to save to a .CSV file, you can use write.csv2 (the 2 indicates that it will be in Brazilian / European format)

write.csv2(dados_agregados, 'Aniversarios.csv')
    
08.01.2015 / 20:20