R filter sets

Asked

Viewed 242 times

3

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

I have an anniversary dataframe with the following format

Months | Person

Abril Joao

Março Ana

Abril Carlos

Junho Joana

Março Pedro

and wanted a genre output

March - Ana, Pedro

April - Joao ,Carlos

June - Joana

I’m using Unicorn(df$months) and I get the only months but I’m not getting to each month select all people

I was thinking of keeping the indices of each Unique(df$months) and then selecting the names of those indices...this for each Unique(df$months). But this does not seem to me to be very "correct" at the level of optimization.

Can anyone help?

Thank you :)

  • Rookie, your problem seems to me to be similar to this question: http://answall.com/questions/11442/colapsar-textos-em-única-linha-numa-base-dados/11443#11443

1 answer

1

A solution to this case would be to use the function aggregate.

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 the NULL after the table. If you want to save to a file . CSV, you can use write.csv2 (2 indicates that it will be in Brazilian/European format)

write.csv2(dados_agregados, 'Aniversarios.csv')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.