-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinal_assignment_my472.Rmd
More file actions
917 lines (835 loc) · 37.1 KB
/
final_assignment_my472.Rmd
File metadata and controls
917 lines (835 loc) · 37.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
---
title: "Final Assignment"
output: html_document
date: "2023-12-26"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(rvest)
library(dplyr)
library(RSelenium)
library(spotifyr)
library("jsonlite")
library(dplyr)
library(ggplot2)
library(plotly) #making the ggplot interactive
library(knitr) #For printing table of Outlier Summary
library(tools)
library(patchwork)
```
```{r rs_ranking, include = FALSE, echo = FALSE}
#The code chunks below are commented out as requested on the Instruction of the Assignment, so that it doesn’t run but it still visible in the code appendix.
# ############### Getting Rolling Stones Ranking Info
#
# #Retrieving the information from the Rolling Stones Ranking
# rD <- rsDriver(browser=c("firefox"), verbose = F, chromever = NULL)
#
# driver <- rD[["client"]]
# url <- "https://www.rollingstone.com/music/music-lists/100-greatest-artists-147446/"
#
# #Navigating to the URL
# driver$navigate(url)
#
# #Allowing the page to load
# Sys.sleep(2)
#
# #Rejecting cookies
# cookie <- driver$findElement(using = 'css', value = '#onetrust-reject-all-handler')
# cookie$clickElement()
#
# #Getting to the bottom of the page
# # loading all the dynamic html
# webElem <- driver$findElement("css", "body")
# webElem$sendKeysToElement(list(key = "end"))
#
# #Getting the full page html
# page_source <- driver$getPageSource()[[1]]
#
# #Extracting the rankings
# html_elements_ranking <- read_html(page_source) %>%
# html_nodes(".c-gallery-vertical-album__number") %>% html_text()
#
# #Extracting the Artists for each ranking
# html_elements_titles <- read_html(page_source) %>%
# html_nodes(".c-gallery-vertical-album__title") %>% html_text()
#
# #Finding the load_more button
# load_more <- driver$findElement(using = 'css', value = ".c-gallery-vertical__load-button")
# load_more$clickElement()
#
# #Going to the bottom of the page to load every artist
# webElem <- driver$findElement("css", "body")
# webElem$sendKeysToElement(list(key = "end"))
#
# #Getting the full page html
# page_source <- driver$getPageSource()[[1]]
#
# #Extracting the rankings
# html_elements_ranking <- c(html_elements_ranking, read_html(page_source) %>%
# html_nodes(".c-gallery-vertical-album__number") %>% html_text())
#
# #Extracting the Artists for each ranking
# html_elements_titles <- c(html_elements_titles, read_html(page_source) %>%
# html_nodes(".c-gallery-vertical-album__title") %>% html_text())
#
# #Closing the port
# driver$close()
# rD$server$stop()
#
# # close the associated Java processes if necessary:
# system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)
#
# #Transforming the data into a Dataframe
# rankings_df <- data.frame(ranking = html_elements_ranking, artist = html_elements_titles)
#
# # Save the data frame as a RDS file
# #saveRDS(rankings_df, "./data/rs_ranking.rds")
```
```{r artist_info_ranking, include = FALSE, echo = FALSE}
# ############### Getting Spotify Info for Every Artist in the RS Ranking
#
# #Reading the client ID and Secret to access the API
# readRenviron("api.env")
# client_id <- Sys.getenv("SPOTIFY_CLIENT_ID")
# client_secret <- Sys.getenv("SPOTIFY_CLIENT_SECRET")
#
# #Generating the access_token
# access_token <- get_spotify_access_token(client_id, client_secret)
#
# #Retrieving the information from the Rolling Stones Ranking
# rs_ranking <- readRDS("./data/rs_ranking.rds")
#
# #Creating a DF to store the data
# artist_id_pop <- data.frame()
#
# # Loop through each artist in the Rolling Stones Ranking
# for (artist in rs_ranking$artist){
# q <- artist
# print(q)
# # Search for the artist on Spotify
# # and getting only the first result
# result <- search_spotify(
# q,
# type = "artist",
# market = NULL,
# limit = 1,
# offset = 0,
# include_external = NULL,
# authorization = access_token,
# include_meta_info = FALSE
# )
#
# new_row <- data.frame(result)
#
# # Add artist name and Spotify data to the dataframe
# new_row <- cbind(artist_rs = q, new_row)
# artist_id_pop <- rbind(artist_id_pop, new_row)
# }
#
# #Save the initial result as a RDS file to avoid having to make new calls to the API
# #saveRDS(artist_id_pop, file = "./data/artist_id_pop_spotify.rds")
#
# #Loading the data that was saved
# artist_id_pop <- readRDS("./data/artist_id_pop_spotify.rds")
#
# # Checking for differences on the artist of the Ranking
# # and the result retrieved from the API
# for (i in 1:nrow(artist_id_pop)){
# if (artist_id_pop$name[i] != artist_id_pop$artist_rs[i]){
# print(paste("different name on index", i))
# print(paste("1 -",artist_id_pop$name[i]))
# print(paste("2 -",artist_id_pop$artist_rs[i]))
# }
# }
#
# #Differences are minor or non relevant (eg. &, and; upper and lower case differences)
# #Only notable differences are:
# # - Santana and Carlos Santana -> Sticking to the id provided by spotify that is the verified artist
# # - Hank Williams brought the Hank Williams Jr singer. Must be replaced by Hank Williams with the artist ID of '1FClsNYBUoNFtGgzeG74dW'
# # - Differences on line 43 "1 - George Clinton & Parliament Funkadelic" - "2 - Parliament and Funkadelic"
#
# #Retrieving the correct information on the wrong artists
#
# #Getting the ids of the artists that are wrong
# #Parliament and Funkadelic
# par_fun_wrong_id <- artist_id_pop %>% filter(artist_rs == "Parliament and Funkadelic") %>% pull(id)
# #Hank Williams
# hank_wil_wrong_id <- artist_id_pop %>% filter(artist_rs == "Hank Williams") %>% pull(id)
#
# #Doing the search again to check for better results
# result <- search_spotify(
# "Parliament Funkadelic",
# type = "artist",
# market = NULL,
# limit = 20,
# offset = 0,
# include_external = NULL,
# authorization = get_spotify_access_token(),
# include_meta_info = FALSE
# )
#
# #Selecting the lines of the band Parliament and the band Funkadelic
# result_par <- subset(result, id == "5SMVzTJyKFJ7TUb46DglcH")
# new_row_p <- cbind(artist_rs = "Parliament and Funkadelic", result_par)
# result_fun <- subset(result, id == "450o9jw6AtiQlQkHCdH6Ru")
# new_row_f <- cbind(artist_rs = "Parliament and Funkadelic", result_fun)
# #Removing the line with the wrong result
# artist_id_pop <- subset(artist_id_pop, id != par_fun_wrong_id)
# #Adding the new lines
# new_row <- rbind(new_row_p, new_row_f)
# artist_id_pop <- rbind(artist_id_pop, new_row)
#
# #Getting Hank Williams info
# result <- search_spotify(
# "Hank Williams",
# type = "artist",
# market = NULL,
# limit = 20,
# offset = 0,
# include_external = NULL,
# authorization = get_spotify_access_token(),
# include_meta_info = FALSE
# )
#
# #Getting the row with the correct result
# result_hank_wil <- subset(result, id == "1FClsNYBUoNFtGgzeG74dW")
# new_row <- cbind(artist_rs = "Hank Williams", result_hank_wil)
# #Removing the row that was wrong
# artist_id_pop <- subset(artist_id_pop, id != hank_wil_wrong_id)
# artist_id_pop <- rbind(artist_id_pop, new_row)
#
# #Saving the dataset as a RDS file
# #saveRDS(artist_id_pop, file = "./data/artist_id_pop.rds")
#
# #Retrieving the data
# artist_id_pop <- readRDS("./data/artist_id_pop.rds")
#
# # Merging the two dataframes, to get one dataset with
# # with the Rolling Stones Ranking and the Spotify data
# artist_info_ranking <- merge(rs_ranking, artist_id_pop,
# by.x = "artist", by.y = "artist_rs",
# all.x = TRUE)
#
# #Changing the names of columns
# artist_info_ranking <- artist_info_ranking %>% rename(artist_rs = artist,
# artist_spotify = name)
#
# # Reorder columns
# artist_info_ranking <- artist_info_ranking %>%
# select(ranking, artist_rs, artist_spotify, id, everything())
#
# artist_info_ranking <- artist_info_ranking[order(artist_info_ranking$ranking), ]
#
# #Correcting the name on the artist_rs column for Parliament and Funkadelic
# artist_info_ranking <- artist_info_ranking %>%
# mutate(artist_rs = ifelse(artist_rs == "Parliament and Funkadelic",
# paste0("Parliament and Funkadelic (", artist_spotify, ")"),
# artist_rs))
#
# # Save the merged dataframe as an RDS file
# #saveRDS(artist_info_ranking, file = "./data/artist_info_ranking.rds")
```
```{r spotify_toptracks, include = FALSE, echo = FALSE}
# ############### Getting Top Tracks for Every Artist in the RS Ranking
#
# #Retrieving the necessary RDS File
# artist_info_ranking <- readRDS("./data/artist_info_ranking.rds")
#
# #Getting the top tracks of each artist in the us
# #Setting the access_token
# access_token <- get_spotify_access_token(client_id, client_secret)
#
# # Creating an empty dataframe to store top tracks
# top_tracks_us <- data.frame()
#
# # Loop through each artist in the ranking dataframe
# for (i in 1:nrow(artist_info_ranking)){
# # Get the Spotify ID of the artist
# id <- artist_info_ranking$id[i]
#
# # Get the top tracks of the artist in the US
# result <- get_artist_top_tracks(
# id,
# market = "US",
# authorization = access_token,
# include_meta_info = FALSE
# )
# # Print the artist's name for visibility
# print(artist_info_ranking$artist_rs[i])
#
# # Assume that the main artist of the track is the one we are looking for
# result$artists <- id
#
# # Include the name of the artist for better readability
# result$artist_spotify <- artist_info_ranking$artist_spotify[i]
#
# # Append the new rows to the dataframe
# new_rows <- result
# top_tracks_us <- rbind(top_tracks_us, new_rows)
# }
#
# # Changing column names for consistency
# for (name in c("id", "name", "popularity", "preview_url")){
# colnames(top_tracks_us)[colnames(top_tracks_us) == name] <- paste0("track_",name)
# }
#
# # Renaming the "artists" column to "artist_id"
# colnames(top_tracks_us)[colnames(top_tracks_us) == "artists"] <- "artist_id"
#
# # Reordering columns for better readability
# top_tracks_us <- top_tracks_us %>%
# select(artist_spotify, artist_id, track_name, track_popularity, track_id, everything())
#
# # Saving the dataframe as an RDS file
# #saveRDS(top_tracks_us, file = "./data/top_tracks_us.rds")
```
```{r spotify_audio_features, include = FALSE, echo = FALSE}
# ############### Getting audio features for all the top tracks US
#
#
# # Setting the access_token
# access_token <- get_spotify_access_token(client_id, client_secret)
#
# # Creating an empty dataframe to store audio features
# audio_features_us <- data.frame()
#
# # Initializing vectors to store track information
# track_list <- c(NULL)
# artist_id <- c(NULL)
# artist_spotify <- c(NULL)
#
# # Loop through each track in the top tracks US dataframe
# for (i in 1:nrow(top_tracks_us)){
# # Get the track ID
# track <- top_tracks_us$track_id[i]
#
# # Append track information to vectors
# track_list <- c(track_list, track)
# artist_id <- c(artist_id, top_tracks_us$artist_id[i])
# artist_spotify <- c(artist_spotify, top_tracks_us$artist_spotify[i])
#
# # If 100 tracks are accumulated or it's the last iteration, get audio features
# if (length(track_list) == 100 | i == nrow(top_tracks_us)){
# result <- get_track_audio_features(track_list,
# authorization = access_token)
#
# # Combine audio features with artist information
# new_rows <- cbind(result, artist_id)
# new_rows <- cbind(new_rows, artist_spotify)
#
# # Append the new rows to the dataframe
# audio_features_us <- rbind(audio_features_us, new_rows)
#
# # Restarting the track list and related vectors
# track_list <- c(NULL)
# artist_id <- c(NULL)
# artist_spotify <- c(NULL)
# }
# }
#
# # Renaming the "id" column to "track_id"
# colnames(audio_features_us)[colnames(audio_features_us) == "id"] <- "track_id"
#
# # Saving the dataframe as an RDS file
# #saveRDS(audio_features_us, file = "./data/audio_features_us.rds")
```
```{r scraping_music_brainz_data, include = FALSE, echo = FALSE}
# ############### Scraping the music Brainz website
# ############### to get information on the end of each artist
# #
#
# # Reading the artist information from a saved RDS file
# artist_info_ranking <- readRDS("./data/artist_info_ranking.rds")
#
# # Setting up a WebDriver for scraping MusicBrainz website
# rD <- rsDriver(browser=c("firefox"), verbose = F, chromever = NULL)
# driver <- rD[["client"]]
# url <- "https://musicbrainz.org/"
#
# # Navigating to the MusicBrainz website
# driver$navigate(url)
#
# # Creating empty dataframes to store MusicBrainz data
# mbdata <- data.frame()
# all_results <- data.frame()
#
# # Looping through each artist in the Rolling Stones ranking
# for (artist in artist_info_ranking$artist_spotify){
# # Find the search field and perform the search
#
# # Performing a search for each artist on MusicBrainz
# while (TRUE){
# # printing the artist that is being searched
# print(artist)
#
# # Finding the search field and performing the search
# search_field <- driver$findElement(using = 'css', value = '#headerid-query')
# search_field$sendKeysToElement(list(artist))
# search_field$sendKeysToElement(list(key = "enter"))
#
# # Giving time for the search results to show
# Sys.sleep(2)
#
# # Getting the search results
# search_results <- try(driver$findElement(using = 'css', value = ".tbl"), silent = TRUE)
#
# # If there is an internal error, try the search again
# if ("try-error" %in% class(search_results)){
# print("Trying search again")
# Sys.sleep(2)
# } else {break}
# }
#
# # Extracting the outer HTML of the table
# results_html <- search_results$getElementAttribute("outerHTML")
#
# #Reading the HTML element of the results
# results_html <- read_html(results_html[[1]])
#
# #Extracting the table of the results
# results_table <- html_table(results_html)[[1]]
#
# #selecting the first row as the correct result
# new_row <- results_table[1,]
# new_row <- cbind(artist_spotify = artist, new_row)
# mbdata <- rbind(mbdata, new_row)
#
# #Saving all other results in case there is mismatch
# result_rows <- cbind(artist_spotify = artist, results_table)
# all_results <- rbind(all_results, result_rows)
# }
#
# # Closing the port
# driver$close()
# rD$server$stop()
#
# # close the associated Java processes if necessary:
# system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)
#
# # Correcting the result for The Drifters that found a Taiwanese group
# the_drifters <- all_results[(all_results$artist == "The Drifters"),]
# #The correct result is the second row
# the_drifters <- the_drifters[2,]
#
# # replacing the row in the mbdata dataframe
# # Finding the index of the original data
# drifters_index <- which(mbdata$artist == "The Drifters")
# # Update the corresponding row in mbdata with the corrected information
# mbdata[drifters_index, ] <- the_drifters
#
#
# # Treating the Begin and End dates to make them in a uniform format
# # If there is only the year and month, the day 01 is assigned
# # If there is only the year, the first of july of the year is assigned
#
# mbdata$Begin <- ifelse(nchar(mbdata$Begin) == 4, paste0(mbdata$Begin, "-07-01"), mbdata$Begin)
# mbdata$Begin <- ifelse(nchar(mbdata$Begin) == 7, paste0(mbdata$Begin, "-01"), mbdata$Begin)
#
# mbdata$End <- ifelse(is.na(mbdata$End), "", mbdata$End)
# mbdata$End <- ifelse(nchar(mbdata$End) == 4, paste0(mbdata$End, "-07-01"), mbdata$End)
# mbdata$End <- ifelse(nchar(mbdata$End) == 7, paste0(mbdata$End, "-01"), mbdata$End)
#
# #Saving the mbdata as a RDS file to be loaded later
# #saveRDS(mbdata, ".\data\mbdata.rds")
```
```{r most_popular_info, include=FALSE, echo=FALSE}
# ############### Retrieving information of the Most Popular Artists today
# ############### Retrieving their top tracks and audio features on Spotify
#
#
# # Setting the URL for the webpage with Spotify's most popular artists
# url <- "https://chartmasters.org/spotify-most-popular-artists/"
#
# # Reading HTML content from the webpage
# html_content <- read_html(url)
#
# # Extracting tabular data from the HTML content
# tab <- html_table(html_content, fill = TRUE)
# popular_artists <- tab[[1]]
#
# # Renaming columns for better readability
# colnames(popular_artists) <- c("rank",
# "artist_img",
# "artist_cm",
# "popularity",
# "weekly +/-",
# "daily Streams")
#
# # Removing unnecessary columns
# popular_artists <- popular_artists %>% select(-artist_img, -"weekly +/-", - popularity)
#
# ### Getting the Spotify id for these artists
#
# # Getting the info to access the API
# readRenviron("api.env")
# client_id <- Sys.getenv("SPOTIFY_CLIENT_ID")
# client_secret <- Sys.getenv("SPOTIFY_CLIENT_SECRET")
# access_token <- get_spotify_access_token(client_id, client_secret)
#
# # Creating dataframe to store information
# spotify_id <- data.frame()
# # Looping through each artist in the popular_artists dataframe
# for (artist in popular_artists$artist_cm){
# q <- artist
# print(q)
#
# result <- search_spotify(
# q,
# type = "artist",
# market = NULL,
# limit = 1,
# offset = 0,
# include_external = NULL,
# authorization = access_token,
# include_meta_info = FALSE
# )
#
# # Creating a new row with the obtained result
# new_row <- data.frame(result)
# new_row <- cbind(artist_cm = q, new_row)
# spotify_id <- rbind(spotify_id, new_row)
# }
#
# # Selecting the relevant information
# spotify_id <- spotify_id %>% select(artist_cm, artist_spotify = name, artist_id = id, genres, popularity)
#
# # Checking for different names
# indices <- which(spotify_id$artist_spotify != spotify_id$artist_cm)
#
# if (length(indices) > 0) {
# print(paste("Different name on indices:", indices))
# print(paste("1 -", spotify_id$artist_spotify[indices]))
# print(paste("2 -", spotify_id$artist_cm[indices]))
# }
#
# # The differences don't seem relevant, no other measures needed
#
# # Merging the two datasets (most popular artists and spotify IDs)
# spotify_id_subset <- spotify_id %>% select(artist_cm, artist_spotify, artist_id, artist_popularity = popularity)
#
# popular_artists <- merge(popular_artists, spotify_id_subset, by = "artist_cm")
#
# #Rearranging the columns
# popular_artists <- popular_artists %>% select(rank,
# artist_cm,
# artist_spotify,
# everything()) %>% arrange(rank)
#
# # Saving the merged dataframe as an RDS file
# #saveRDS(popular_artists, "./data/popular_artists_cm.rds")
#
# #loading the information
# popular_artists <- readRDS("./data/popular_artists_cm.rds")
#
# #Getting the top tracks of each artist in the us
# #Setting the access_token
# access_token <- get_spotify_access_token(client_id, client_secret)
#
# pop_top_tracks_us <- data.frame()
# # Looping through each artist in the popular_artists dataframe
# for (i in 1:nrow(popular_artists)){
# id <- popular_artists$artist_id[i]
#
# # Getting the top tracks of the artist in the US
# result <- get_artist_top_tracks(
# id,
# market = "US",
# authorization = access_token,
# include_meta_info = FALSE
# )
# print(popular_artists$artist_spotify[i])
#
# # Assuming that the main artist of the track is the one that we are looking for
# result$artists <- id
#
# # Including the name of the artist for better readability
# result$artist_spotify <- popular_artists$artist_spotify[i]
#
# # Appending the new rows to the dataframe
# new_rows <- result
# pop_top_tracks_us <- rbind(pop_top_tracks_us, new_rows)
# }
#
# #selecting the relevant columns
# pop_top_tracks_us <- pop_top_tracks_us %>% select(artist_spotify,
# artist_id = artists,
# track_id = id,
# track_name = name,
# track_popularity = popularity,
# album.release_date,
# album.release_date_precision,
# )
#
# # Getting audio features for all the top tracks in the US
# pop_audio_features_us <- data.frame()
# track_list <- c(NULL)
# artist_id_list <- c(NULL)
# artist_list <- c(NULL)
#
# # Looping through each track in the pop_top_tracks_us dataframe
# for (i in 1:nrow(pop_top_tracks_us)){
#
# track <- pop_top_tracks_us$track_id[i]
# track_list <- c(track_list, track)
# artist_id_list <- c(artist_id_list, pop_top_tracks_us$artist_id[i])
# artist_list <- c(artist_list, pop_top_tracks_us$artist_spotify[i])
#
# # If 100 tracks are accumulated or it's the last iteration, get audio features
# if (length(track_list) == 100 | i == nrow(pop_top_tracks_us)){
# result <- get_track_audio_features(track_list,
# authorization = access_token)
#
# # Combining audio features with artist information
# new_rows <- cbind(result, artist_id = artist_id_list)
# new_rows <- cbind(new_rows, artist_spotify = artist_list)
#
# # Appending the new rows to the dataframe
# pop_audio_features_us <- rbind(pop_audio_features_us, new_rows)
#
# # Restarting the track list and related vectors
# track_list <- c(NULL)
# artist_id_list <- c(NULL)
# artist_list <- c(NULL)
# }
# }
# # Renaming the "id" column to "track_id"
# colnames(pop_audio_features_us)[colnames(pop_audio_features_us) == "id"] <- "track_id"
# pop_audio_features_us_subset <- pop_audio_features_us %>% select (-artist_spotify)
#
# # Merging the top tracks and the audio features
# pop_audio_features_us <- merge(pop_top_tracks_us,
# pop_audio_features_us_subset,
# by.x = c("track_id", "artist_id"),
# by.y = c("track_id", "artist_id"))
#
#
# # Saving the merged dataframe as an RDS file
# #saveRDS(pop_audio_features_us, "./data/popular_artists_audio_features.rds")
```
```{r cleaning_environment, include=FALSE, echo = FALSE}
# # All the data has been retrieved and processed
# # Whenever needed the data will be directly loaded
# # Cleaning the environment for better performance
#
# rm(list = ls())
```
**Github repository:** 'https://github.com/editor210/MY_472_Final_Assignment'
#### **1. Introduction**
This research endeavors to explore how the music of the ["100 Greatest Musical Artists of All Time"](https://www.rollingstone.com/music/music-lists/100-greatest-artists-147446/), according to Rolling Stones (RS) magazine, endured at the close of 2023.The analysis comprises three stages, analysing Spotify popularity, examining the impact of the time of the releases on popularity and evaluating the tracks audio features and their current popularity.
#### **2. Data**
Various data sources were used to explore this topic:
1. Data retrieved via webscraping
- ["100 Greatest Musical Artists of All Time"](https://www.rollingstone.com/music/music-lists/100-greatest-artists-147446/) - Artists and ranking positions
- [MusicBrainz](https://musicbrainz.org/) - Life Span of each of the Ranked Artists
- [ChartMaster](https://chartmasters.org/spotify-most-popular-artists/) - List of today's most popular artists.
2. Other Sources
- [Spotify API](https://developer.spotify.com/documentation/web-api): Utilized the [spotifyr](https://www.rdocumentation.org/packages/spotifyr/versions/2.2.4) package for artist searches, top tracks retrieval, and audio features extraction.
The data processing involved retrieving the data, treating the datasets maintaining either the artists id, the track id or a combination of both as a primary key. After the processing of the information the data was saved as a RDS file.
Key decisions during this stage included treating Parliament and Funkadelic as separate bands due to their recent merger, resulting in a final ranking of 101 artists. Additionally, the decision to use an RDS file, as a more efficient choice, instead of a relational database due to the complexity of flattening variables within dataframes from the Spotify API.
#### **3. Analysis**
##### **3.1 Popularity Analysis**
Spotify's popularity index will be used to assess the endurance of the RS ranked artists' music. This index for an artist is based on each artists' track popularity, which, according to the Spotify documentation, has a high weight on the current popularity, since "songs that are being played a lot now will have a higher popularity than songs that were played a lot in the past". Given the range of 0 to 100, and assuming a normal distribution of popularity among Spotify artists, this study will classify those with a popularity index over 50 as "Popular", while those below are "Unpopular".
The interactive plot below shows each artist's RS Ranking position versus their current Spotify popularity. Dot colors indicate popularity.
```{r warning=FALSE, include = FALSE, echo = FALSE}
#loading the needed datasets
artist_info_ranking <- readRDS("./data/artist_info_ranking.rds")
# Define artist popularity based on a threshold of 50
artist_info_ranking$is_popular <- ifelse(artist_info_ranking$popularity > 50,
"Popular",
"Not Popular")
# Create a new dataset to use in the plot
# with additional columns and arrange the data
plot_one_data <- artist_info_ranking %>%
# New Column with followers in thousands and round to 2 decimal places
mutate(followers_k = round(followers.total/1000, 2)) %>%
# Convert artist_spotify to a factor
mutate(artist_spotify = factor(artist_spotify, artist_spotify)) %>%
# Prepare text for tooltip in interactive plot
mutate(text = paste("Artist: ", artist_spotify,
"\nPopularity on Spotify: ", popularity,
"\nRanking Rolling Stones: ", ranking,
"\nFollowers (1,000): ", followers_k, sep=""))
# Create a ggplot scatter plot with a smooth line and additional formatting
p1 <- plot_one_data %>%
ggplot() +
geom_point(aes(x = ranking, y = popularity, color = is_popular, text = text), size = 3, alpha = 0.5) +
theme_minimal() +
labs(title = "Rolling Stones Ranking x Spotify Popularity",
color = NULL,
x = "Rolling Stones Ranking",
y = "Spotify Popularity") +
ylim(0, 100) +
xlim(0, 100) +
geom_vline(xintercept = 0, color = "black", alpha = 0.1) + # Add vertical line at x = 0
geom_hline(yintercept = 0, color = "black", alpha = 0.1) + # Add horizontal line at y = 0
theme(legend.position = "bottom",
panel.grid = element_line(color = alpha("gray", 0.2), linetype = "dashed"), # Adjust legend position
axis.text = element_text(size = 8), # Adjust axis text size
axis.title = element_text(size = 10),
plot.title = element_text(hjust = 0.5)) # Adjust axis title size
# Convert ggplot plot to plotly for interactivity with tooltips
p1_int <- ggplotly(p1, tooltip = "text")
```
```{css, echo=FALSE}
/* Centering the Plotly interactive plot*/
/*Source: https://stackoverflow.com/questions/47193192/r-markdown-and-plotly-fig-align-not-working-with-html-output*/
.center {
display: table;
margin-right: auto;
margin-left: auto;
}
```
<div class = 'center'>
```{r, include = TRUE, echo = FALSE, fig.width = 6, fig.height = 3, fig.align='center'}
#Plotting the graph
p1_int
```
</div>
From the plot above, it is clear that, the vast majority of artists in the RS ranking and, consequently theirs songs, have endured and can be considered popular by the end of 2023.
##### **3.2 Time and Artist's Status Impact on Popularity**
The artist's current popularity can be influenced by the song's release date and the artist's status. Older songs may lose relevance, and the artist's ongoing activity can impact popularity.
Combining Spotify API album release dates with artist lifespan data from [MusicBrainz.org](https://musicbrainz.org/), the graph below plots top tracks in the United States market for RS artists as "Regular Release" if the artist was active and "Releases of Non-Active Artist" otherwise, while comparing the tracks's popularity versus the date of the release.
```{r, include = FALSE, echo = FALSE}
artist_info_ranking <- readRDS("./data/artist_info_ranking.rds")
top_tracks_us <- readRDS("./data/top_tracks_us.rds")
mbdata <- readRDS("./data/mbdata.rds")
#Selecting the necessary variables from each of the datasets
subset_mbdata <- mbdata %>% select(artist_spotify, Begin, End)
subset_artist_info_ranking <- artist_info_ranking %>% select(artist_spotify, artist_id = id, popularity)
subset_top_tracks_us <- top_tracks_us %>% select(artist_spotify, artist_id, track_name, track_id, track_popularity, album.release_date)
merge_data_p3 <- merge(subset_mbdata, subset_artist_info_ranking, by = "artist_spotify")
merge_data_p3 <- merge(merge_data_p3, subset_top_tracks_us, by = "artist_id")
# Convert dates to Date objects
merge_data_p3$Begin <- as.Date(merge_data_p3$Begin)
merge_data_p3$End <- as.Date(merge_data_p3$End)
merge_data_p3$album.release_date <- as.Date(merge_data_p3$album.release_date)
merge_data_p3$band_ended <- ifelse(merge_data_p3$End < merge_data_p3$album.release_date, "Release of Non Active Artist", "Regular Release")
merge_data_p3$band_ended[is.na(merge_data_p3$band_ended)] <- "Regular Release"
merge_data_p3$is_pop <- ifelse(merge_data_p3$popularity > 50, "Popular Artist", "Unpopular Artist")
average_popularity <- merge_data_p3 %>%
group_by(band_ended) %>%
summarise(avg_popularity = mean(popularity))
plot_data <- merge_data_p3 %>% filter(!is.na(album.release_date))
```
```{r fig.width=11, message=FALSE, warning=FALSE, echo = FALSE, include = TRUE}
# Create the plot for band_ended facet
p2 <- ggplot(plot_data %>% filter(is_pop == "Popular Artist"), aes(x = album.release_date, y = track_popularity, color = band_ended)) +
geom_point(size = 3, alpha = 0.7) +
scale_x_date(date_breaks = "5 years", date_labels = "%Y", limits = c(as.Date("1958-01-01"), as.Date("2023-12-12") )) +
labs(title = "Track Popularity Over Album Release Dates",
subtitle = "'Popular' Artists",
x = "Album Release Date",
y = "Track Popularity",
color = "") +
theme_minimal() +
ylim(0,100) +
geom_smooth(method = "lm", se = FALSE) +
theme(legend.position = "bottom",
axis.text.x = element_text(angle = 45),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_line(linetype = "dashed"),
panel.grid.major.y = element_line(linetype = "dashed"),
plot.title = element_text(size = 16, hjust = 0.5, color = "black", face = "bold"),
plot.subtitle = element_text(size = 12, hjust = 0.5, color = "black")) +
geom_hline(aes(yintercept = 0), linetype = "solid", color = "black", alpha = 0.5)
p3 <- ggplot(plot_data %>% filter(is_pop != "Popular Artist"), aes(x = album.release_date, y = track_popularity, color = band_ended)) +
geom_point(size = 3, alpha = 0.7) +
scale_x_date(date_breaks = "5 years", date_labels = "%Y", limits = c(as.Date("1958-01-01"), as.Date("2023-12-12") )) +
labs(title = "Track Popularity Over Album Release Dates",
subtitle = "'Unpopular' Artists",
x = "Album Release Date",
y = "Track Popularity",
color = "") +
theme_minimal() +
ylim(0,100) +
#xlim(as.Date("1960-01-01"), NA) +
geom_smooth(method = "lm", se = FALSE)+
theme(legend.position = "bottom",
axis.text.x = element_text(angle = 45),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_line(linetype = "dashed"),
panel.grid.major.y = element_line(linetype = "dashed"),
plot.title = element_text(size = 16, hjust = 0.5, color = "black", face = "bold"),
plot.subtitle = element_text(size = 12, hjust = 0.5, color = "black")) +
geom_hline(aes(yintercept = 0), linetype = "solid", color = "black", alpha = 0.5)
# Display the plots side by side
library(gridExtra)
grid.arrange(p2, p3, ncol = 2)
```
Notably, pre-1995 releases dominate, which is expected given the historical figures in the RS ranking.
The first plot lack significant correlation while the second graph suggests a connection between release time and popularity. Interestingly, recent releases boost non-active artists’ popularity but reduce it for active artists. Without making any causality claims, this suggests that an artist’s end may enhance long-term popularity, by having multiple hits while active, or by the relaunching of old hits during inactive periods.
##### **3.3 Audio Feature Analysis**
Next, this study explores audio features in the US top tracks of today's [50 most popular artists](https://chartmasters.org/spotify-most-popular-artists/) versus RS ranked popular and unpopular artists. Plots below display density distributions of tracks' Audio Features, colored by artists' popularity.
```{r, fig.height=20, include=FALSE, echo=FALSE}
# Merge the dataframes based on artist_spotify
artist_info_ranking <- readRDS("./data/artist_info_ranking.rds")
top_tracks_us <- readRDS("./data/top_tracks_us.rds")
audio_features_us <- readRDS("./data/audio_features_us.rds")
#First we need to merge the artist_info_ranking and the audio_feature_us to determine the popular and non popular artists
artist_info_ranking_subset <- artist_info_ranking %>% select(artist_id = id, popularity)
audio_features_us_merged <- merge(audio_features_us, artist_info_ranking_subset, by = "artist_id")
#Creating the column is_pop in the audio_features_us_merged
audio_features_us_merged$is_pop <- ifelse(audio_features_us_merged$popularity > 50, "Popular", "Unpopular")
#Importing the data from the popular artists of 2023 audio features
popular_art_aud_feat <- readRDS("./data/popular_artists_audio_features.rds")
#Creating a column to indicate that these are the most popular artists
popular_art_aud_feat$is_pop <- "Most Popular Today"
#Selecting the columns that will be analised
subset_cols <- c("artist_spotify",
"track_id",
"artist_id",
"is_pop",
"danceability",
"energy",
"loudness",
"mode",
"speechiness",
"acousticness",
"instrumentalness",
"liveness",
"valence",
"tempo")
#Creating the subsets that will be merged to be plotted
audio_features_us_subset <- audio_features_us_merged %>% select(all_of(subset_cols))
popular_art_aud_feat_subset <- popular_art_aud_feat %>% select(all_of(subset_cols))
#The dfs have the same columns, so we will just rbind them
audio_feature_plot_data <- rbind(audio_features_us_subset, popular_art_aud_feat_subset)
# Select relevant columns for comparison
comparison_cols <- c("danceability",
"energy",
"loudness",
"speechiness",
"acousticness",
"liveness",
"valence",
"tempo")
```
```{r fig.height=10, fig.width = 10, include=TRUE, echo=FALSE}
custom_colors <- c("#1F78B4", "#FF7F00", "#33A02C")
#Plotting based on artist popularity
plots <- lapply(comparison_cols, function(col) {
ggplot(audio_feature_plot_data, aes(x = get(col), fill = is_pop)) +
geom_density(alpha = 0.3) +
scale_fill_manual(values = custom_colors) +
labs(title = paste("Density Plot of", toTitleCase(as.character(col))),
x = col,
fill = "Artist Popularity") +
theme_minimal()+
theme(legend.position = "bottom",
plot.title = element_text(hjust = 0.5))
})
# Arrange plots in a grid with 3 columns
grid_plots <- wrap_plots(plots, ncol = 2)
# Display the grid of plots
print(grid_plots)
```
Due to word limit constraints, the discussion will focus on features with significant differences, not mentioning features’ [definitions](https://developer.spotify.com/documentation/web-api/reference/get-audio-features).
In summary, today's most successful music exhibits higher danceability (around 0.75 energy level), is quieter, less acoustic, released in the studio version (lower liveness), and with lower valence. Notably, Popular Top 100 artists align more with today's most popular artists in energy, loudness, acousticness, and liveness, suggesting audio features may impact track and artist endurance.
The difference in the Valence feature is also interesting. According to Spotify, this feature reflects overall positiveness of the song, whereas low valence indicates a more negative tone (e.g. sad, depressed, angry). Further analysis could investigate the relationship of this change with broader societal issues over time.
##### **3.4 Conclusion**
This study analyzed how the music from the artists of the top 100 Rolling Stones has endured. Results show that the majority of the artists and their songs, have succeeded against time. The number of hits, relaunching old successes, and song audio features may impact current popularity. Further studies may explore causality and test these findings globally.
## Appendix: All code in this assignment
```{r ref.label=knitr::all_labels(), echo=TRUE, eval=FALSE}
# this chunk generates the complete code appendix.
# eval=FALSE tells R not to run (``evaluate'') the code here (it was already run before).
```