我在 R 中有一個音樂資料,我必須按流派對資料進行分組,計算每個流派中的流總數,并對結果進行排序以首先顯示最受歡迎的流派。
我已經撰寫了這段代碼,但我覺得在對結果進行排序以顯示最流行的流派時我重復了一些步驟。你能幫我簡化這段代碼嗎?
謝謝!
#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
uj5u.com熱心網友回復:
它可以在 tidyverse 中完成
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')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515262.html
標籤:r
上一篇:通過閃亮的按鈕更改地圖上的目的地
