r - 如何在 r 中制作年度音乐排行榜?重复合并不起作用
问题描述
我有一个音乐排行榜数据框 bb1
title artist rank score
1 Thank U, Next Ariana Grande 1 100
2 Without Me Halsey 2 99
3 All I Want For Christmas Is You Mariah Carey 3 98
4 Sicko Mode Travis Scott 4 97
5 Sunflower (Spider-Man: Into The Spider-Verse) Post Malone & Swae Lee 5 96
6 High Hopes Panic! At The Disco 6 95
7 Happier Marshmello & Bastille 7 94
8 Jingle Bell Rock Bobby Helms 8 93
9 Rockin' Around The Christmas Tree Brenda Lee 9 92
10 A Holly Jolly Christmas Burl Ives 10 91
.
.
.
101 Without Me Halsey 1 100
102 Thank U, Next Ariana Grande 2 99
103 Sunflower (Spider-Man: Into The Spider-Verse) Post Malone & Swae Lee 3 98
104 Sicko Mode Travis Scott 4 97
105 High Hopes Panic! At The Disco 5 96
106 Happier Marshmello & Bastille 6 95
107 Girls Like You Maroon 5 Featuring Cardi B 7 94
108 Drip Too Hard Lil Baby & Gunna 8 93
109 ZEZE Kodak Black Featuring Travis Scott & Offset 9 92
110 Better Now Post Malone 10 91
它基本上是每周热门歌曲的汇编。
为了汇编每首歌的“分数”以制作年度前 10 名图表
,我想添加合并每首歌曲的分数并按分数降序排列图表。
所以我尝试了下面的代码
for(i in 1:nrow(bb1)){
if (((bb1[i,1]==bb1[i+1,1])&&(bb1[i,2]==bb1[i+1,2]))){
bb1[i+1,4]<- (bb1[i,4]+bb1[i+1,4])
bb1<-bb1[-c(i),]
i=i+1
}
}
bb1[order(-bb1$score),]
但它并没有像我想要的那样工作。相反,会弹出此错误
Error in if (((bb1[i, 1] == bb1[i + 1, 1]) && (bb1[i, 2] == bb1[i + 1, :
missing value where TRUE/FALSE needed
谁能帮我吗?还有其他更有效的方法来制作年度图表吗?
解决方案
你可以通过使用dplyr
包来做到这一点。在这里,我使用了以下示例:
letter = rep(c("A","B","C"),5)
score = sample(1:100,15)
df = data.frame(letter = letter, score = score)
df
看起来像什么:
> head(df)
letter score
1 A 70
2 B 94
3 C 74
4 A 14
5 B 51
6 C 57
并且使用dplyr
,我们可以计算每组的总和:
> df %>%
+ group_by(letter) %>%
+ summarise(sum_score = sum(score)) %>%
+ arrange(desc(sum_score))
# A tibble: 3 x 2
letter sum_score
<fct> <int>
1 C 329
2 B 288
3 A 265
因此,对于您的数据集,您应该替换letter
为title
(或 和 的组合title
)artist
。
它在回答你的问题吗?
推荐阅读
- arrays - oracle : 编写一个 Oracle FileSize 函数
- python - 这个python openpyxl“ValueError”是什么意思?
- ios - 如何删除文件 Xcode 项目?
- javascript - 为什么只从隐藏字段中获取最后一个 question_id 值...?
- bash - 为什么MacOS终端在复制带有不间断空格的字符串时会切换字符位置?
- scala - 在 gatling 版本升级中,dataDirectory 不是 io.gatling.core.config.GatlingPropertiesBuilder 的成员
- mule - 无法为 GROOVY 脚本解析类 org.ajoberstar.grgit.Grgit
- amazon-web-services - 如何允许订阅模型而不在 auth 指令中指定“更新”操作
- regex - 用于验证数字的正则表达式,带或不带冒号或小数点
- google-cloud-platform - Google Cloud Pub/Sub 推送订阅在消息处理期间重试消息传递