Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I simplify this code in R? Determine the most popular genre and calculate the total number of streams within each genre

I have a music data in R and I have to group the data by genre, calculate the total number of streams within each genre, and sort the result to show the most popular genre first.

I have written this code, but I feel like I repeat some of the steps when sorting the result to show the most popular genre. Could you please help me to simplify this code?

Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#Group the data by genre and calculate the total number of streams
genre <- aggregate(music_data$streams, by = list(music_data$genre), FUN = sum)

#Change the name of the columns
colnames(genre) <- c("genre", "streams")

#Sort the result to show the most popular genre first
genre_sorted <- arrange(genre, desc(streams))
rownames(genre_sorted) <- genre_sorted$genre
genre_grouped_sorted <- subset(genre_sorted, select = c("streams"))
genre_sorted

>Solution :

It can be done in tidyverse as

library(dplyr)
library(tibble)
music_data %>%
    group_by(genre) %>%
    summarise(streams = sum(streams, na.rm = TRUE), .groups = 'drop') %>%
    arrange(genre, desc(streams)) %>%
    column_to_rownames('genre')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading