-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01a_scopus_API_fed.R
More file actions
1803 lines (1507 loc) · 58.3 KB
/
01a_scopus_API_fed.R
File metadata and controls
1803 lines (1507 loc) · 58.3 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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# install.packages("rscopus")
# install.packages("tidyverse")
library(rscopus)
library(tidyverse)
library(data.table)
library(purrr)
library(furrr)
library(future)
# help --------------------------------------------------------------------
# rscopus: https://cran.r-project.org/web/packages/rscopus/vignettes/multi_author.html
# load packages -----------------------------------------------------------
api<-"c253aa47dd592442b1d5ad7ded7b0514"
api_key<-api
set_api_key(api)
# date_folder_for_files<-"fed_20251010"
# date_folder_for_files<-"fed_20251210"
date_folder_for_files<-"fed_20260101"
# res<-get_api_key()
# print(res, reveal = TRUE)
# token is from Scopus dev
# hdr = inst_token_header(token)
# res = author_df(last_name = "Muschelli", first_name = "John", verbose = FALSE, general = FALSE, headers = hdr)
# source("./code/generate_fed_affils_to_search.R")
# affils_to_search<-generate_fed_affils_to_search()
# affils_to_search<-read_csv("./data_clean/api_fed_affils_searched_2025-09-01.csv")
# AFFILS ORIGINALLY SEARCHED
affils_to_search_original<-read_csv("data_clean/api_fed_affils_searched_2025-11-04.csv") %>%
select(affil_id,agency_primary) %>%
distinct()
# FINAL LIST OF AFFILIATIONS FOUND IN DEC AFTER ANALYSIS
affils_to_search_followup <- readRDS("data_clean/affils_df_clean_fed_20251210.rds") %>%
filter(federal==TRUE) %>%
select(affil_id, agency_primary) %>%
distinct() %>%
arrange(agency_primary)
affils_to_search_all<-full_join(affils_to_search_original,
affils_to_search_followup) %>%
distinct()
write_csv(affils_to_search_all,"data_clean/api_fed_affils_searched.csv")
# VA and HHS
search_term_over5K <- as_tibble(c(60014232,
60006577)) %>%
rename(affil_id=value)
# create the folders for download -----------------------------------------
yr1=2019
yr2=2025
date_range <- seq(yr1,yr2)
# setting up the main directory
main_dir <- paste("data_raw/scopus_downloads/",date_folder_for_files,sep="")
sub_dir <- paste(main_dir,"/papers/",yr1,sep="")
if (!dir.exists(sub_dir)){
dir.create(main_dir, recursive = TRUE)
}
date_range <- seq(yr1,yr2+1)
year <- seq_along(date_range)
for (j in year) {
# setting up the sub directories
# papers
# check if sub directory exists
sub_dir <- paste(main_dir,"/papers/",date_range[j],sep="")
# Check if subdirectory exists
if (dir.exists(sub_dir)) {
print("The folder exists!")
} else {
# Create a new subdirectory inside the main path
dir.create(sub_dir, recursive = TRUE)
print("Subdirectory created.")
}
# Authors
sub_dir <- paste(main_dir,"/authors/",date_range[j],sep="")
# Check if subdirectory exists
if (dir.exists(sub_dir)) {
print("The folder exists!")
} else {
# Create a new subdirectory inside the main path
dir.create(sub_dir, recursive = TRUE)
print("Subdirectory created.")
}
sub_dir <- paste(main_dir,"/affils/",date_range[j],sep="")
# Check if subdirectory exists
if (dir.exists(sub_dir)) {
print("The folder exists!")
} else {
# Create a new subdirectory inside the main path
dir.create(sub_dir, recursive = TRUE)
print("Subdirectory created.")
}
}
# IF YOU CAN PARALLELIZE, USE THIS ----------------------------------------
# STEP 1 search initial affiliation IDs by PY ------------------------------
library(furrr)
library(future)
# Set up parallel processing
plan(multisession, workers = 3) # Adjust based on API limits and CPU cores
# Prepare search grid
search_term <- anti_join(affils_to_search_all, search_term_over5K) %>%
select(-agency_primary)
# 2019
yr1 <- 2020
yr2 <- 2021
date_range <- seq(yr1, yr2)
search_df <- expand_grid(search_term, date_range) %>%
arrange(desc(date_range)) %>%
mutate(row_id = row_number())
# search_df<-new_search_df
# Define processing function
process_search <- function(row_data, api, date_folder_for_files) {
j <- row_data$row_id
# Progress reporting
if (j %% 10 == 0) {
cat("Progress:", j, "; term:", row_data$affil_id, "\n")
}
# Build query
a <- paste0("(AF-ID('", row_data$affil_id, "') AND (DOCTYPE(ar) OR DOCTYPE(re) OR DOCTYPE(ch) OR DOCTYPE(ed) OR DOCTYPE(le) OR DOCTYPE(dp) OR DOCTYPE(no))")
b <- paste0(" AND PUBYEAR IS ", row_data$date_range, ")")
query_string <- paste0(a, b)
# API call with error handling
tryCatch({
scopus_data <- rscopus::scopus_search(
query_string,
max_count = 8000,
view = "COMPLETE",
verbose = FALSE,
api_key = api
)
scopus_data_raw <- gen_entries_to_df(scopus_data$entries)
# Check if valid data
if (nrow(scopus_data_raw$df) == 1 & ncol(scopus_data_raw$df) == 3) {
return(list(success = TRUE, skipped = TRUE,
term = row_data$affil_id, year = row_data$date_range))
}
# Extract data
scopus_papers <- scopus_data_raw$df
scopus_affiliations <- scopus_data_raw$affiliation
scopus_authors <- scopus_data_raw$author
# Create file paths
term_for_file <- paste0("scopus_affil_", row_data$affil_id, "_", row_data$date_range)
papers_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/papers/", row_data$date_range, "/", term_for_file, "_papers.csv")
affils_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/affils/", row_data$date_range, "/", term_for_file, "_affils.csv")
authors_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/authors/", row_data$date_range, "/", term_for_file, "_author.csv")
# Write files
suppressMessages({
write_csv(scopus_papers, papers_path)
write_csv(scopus_affiliations, affils_path)
write_csv(scopus_authors, authors_path)
})
return(list(success = TRUE, skipped = FALSE,
term = row_data$affil_id, year = row_data$date_range))
}, error = function(e) {
return(list(success = FALSE, term = row_data$affil_id,
year = row_data$date_range, error = e$message))
})
}
# Run in parallel
results <- future_map(
split(search_df, 1:nrow(search_df)),
~ process_search(.x, api, date_folder_for_files),
.options = furrr_options(seed = TRUE),
.progress = TRUE
)
# Summarize results
successful <- sum(sapply(results, function(x) x$success && !x$skipped))
skipped <- sum(sapply(results, function(x) x$success && x$skipped))
failed <- sum(sapply(results, function(x) !x$success))
cat("\nCompleted:", successful, "successful,", skipped, "skipped (empty),", failed, "failed\n")
# Get failed items
failed_items <- results %>%
keep(~ !.x$success) %>%
map_df(~ tibble(term = .x$term, year = .x$year, error = .x$error))
if (nrow(failed_items) > 0) {
failed_items<-failed_items %>%
rename(date_range=year,
affil_id=term)
cat("\nFailed items:\n")
print(failed_items)
# if cuts out, rerun with these:
new_search_df<-search_df %>%
inner_join(failed_items,by=c("affil_id", "date_range")) %>%
select(affil_id,
date_range) %>%
mutate(row_id=row_number())
}else{
print("Done! No terms failed in the API call.")
}
# Clean up
plan(sequential)
# STEP 2: search original but >5K by upload month ---------------------------
# In these you need to gather by PY and upload month, starting 5 years BEFORE
library(furrr)
library(future)
# Set up parallel processing (adjust workers based on your CPU cores)
# 2019
pub_year <- 2020
search_term <- search_term_over5K$affil_id
months <- sprintf("%02d", 1:12)
final_study_yr <- 2025
date_range <- seq(pub_year - 5, final_study_yr)
search_df <- expand_grid(search_term, months, date_range) %>%
rename(load_mo = months,
load_yr = date_range) %>%
arrange(search_term, load_yr, load_mo) %>%
mutate(row_id = row_number())
# search_df<-new_search_df
plan(multisession, workers = 4) # Use 4 cores, adjust as needed
# Define the processing function
process_search <- function(row_data, pub_year, api, date_folder_for_files) {
j <- row_data$row_id
# Progress reporting (will show in each worker)
if (j %% 12 == 0) {
cat("Progress: term / month / year :",
paste(row_data$search_term, row_data$load_mo, row_data$load_yr, sep = "-"), "\n")
}
# Calculate dates
start_date <- paste0(row_data$load_yr, row_data$load_mo, "01")
if (row_data$load_mo != "12") {
next_month <- sprintf("%02d", as.numeric(row_data$load_mo) + 1)
end_date <- paste0(row_data$load_yr, next_month, "02")
} else {
end_date <- paste0(row_data$load_yr + 1, "01", "02")
}
# Build query
a <- paste0("(AF-ID('", row_data$search_term, "') AND (DOCTYPE(ar) OR DOCTYPE(re) OR DOCTYPE(ch) OR DOCTYPE(ed) OR DOCTYPE(le) OR DOCTYPE(dp) OR DOCTYPE(no))")
b <- paste0(" AND PUBYEAR IS ", pub_year)
c <- paste0(" AND ORIG-LOAD-DATE > ", start_date, " AND ORIG-LOAD-DATE < ", end_date, ")")
query_string <- paste0(a, b, c)
# API call with error handling
tryCatch({
scopus_data <- rscopus::scopus_search(
query_string,
max_count = 8000,
verbose = FALSE,
view = "COMPLETE",
api_key = api
)
scopus_data_raw <- gen_entries_to_df(scopus_data$entries)
# Check if valid data
if (nrow(scopus_data_raw$df) == 1 & ncol(scopus_data_raw$df) == 3) {
return(NULL) # Skip empty results
}
# Extract data
scopus_papers <- scopus_data_raw$df
scopus_affiliations <- scopus_data_raw$affiliation
scopus_authors <- scopus_data_raw$author
# Create file paths
term_for_file <- paste0("scopus_affil_", row_data$search_term, "_",
row_data$load_yr, "_", row_data$load_mo)
papers_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/papers/", pub_year, "/", term_for_file, "_papers.csv")
affils_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/affils/", pub_year, "/", term_for_file, "_affils.csv")
authors_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/authors/", pub_year, "/", term_for_file, "_author.csv")
# Write files
write_csv(scopus_papers, papers_path)
write_csv(scopus_affiliations, affils_path)
write_csv(scopus_authors, authors_path)
return(list(success = TRUE, term = row_data$search_term,
month = row_data$load_mo, year = row_data$load_yr))
}, error = function(e) {
return(list(success = FALSE, term = row_data$search_term,
month = row_data$load_mo, year = row_data$load_yr,
error = e$message))
})
}
# Run in parallel
results <- future_map(
split(search_df, 1:nrow(search_df)),
~ process_search(.x, pub_year, api, date_folder_for_files),
.options = furrr_options(seed = TRUE),
.progress = TRUE
)
# Summarize results
successful <- sum(sapply(results, function(x) !is.null(x) && x$success))
failed <- sum(sapply(results, function(x) !is.null(x) && !x$success))
cat("\nCompleted:", successful, "successful,", failed, "failed\n")
# Clean up
plan(sequential)
failed<-tibble(row_id=which(sapply(results, function(x) !is.null(x) && !x$success)))
if (nrow(failed) > 0) {
new_search_df<-search_df %>%
filter(row_id%in%failed$row_id) %>%
mutate(row_id = row_number())
cat("\nFailed items:\n")
print(failed)
}else{
print("Done! No terms failed in the API call.")
}
# STEP 4: after cleanup ---------------------------------------------------
affils_to_search_followup_after <- readRDS("data_clean/affils_df_clean_fed_20260101.rds") %>%
filter(federal==TRUE) %>%
select(affil_id, agency_primary) %>%
distinct() %>%
arrange(agency_primary)
after_cleanup<-affils_to_search_followup_after %>% anti_join(affils_to_search_all)
library(furrr)
library(future)
# Set up parallel processing
plan(multisession, workers = 2) # Adjust based on API limits and CPU cores
# Prepare search grid
search_term <- after_cleanup %>%
select(-agency_primary)
# 2019
yr1 <- 2020
yr2 <- 2025
date_range <- seq(yr1, yr2)
search_df <- expand_grid(search_term, date_range) %>%
arrange(desc(date_range)) %>%
mutate(row_id = row_number())
# search_df<-new_search_df
# Define processing function
process_search <- function(row_data, api, date_folder_for_files) {
j <- row_data$row_id
# Progress reporting
if (j %% 10 == 0) {
cat("Progress:", j, "; term:", row_data$affil_id, "\n")
}
# Build query
a <- paste0("(AF-ID('", row_data$affil_id, "') AND (DOCTYPE(ar) OR DOCTYPE(re) OR DOCTYPE(ch) OR DOCTYPE(ed) OR DOCTYPE(le) OR DOCTYPE(dp) OR DOCTYPE(no))")
b <- paste0(" AND PUBYEAR IS ", row_data$date_range, ")")
query_string <- paste0(a, b)
# API call with error handling
tryCatch({
scopus_data <- rscopus::scopus_search(
query_string,
max_count = 8000,
view = "COMPLETE",
verbose = FALSE,
api_key = api
)
scopus_data_raw <- gen_entries_to_df(scopus_data$entries)
# Check if valid data
if (nrow(scopus_data_raw$df) == 1 & ncol(scopus_data_raw$df) == 3) {
return(list(success = TRUE, skipped = TRUE,
term = row_data$affil_id, year = row_data$date_range))
}
# Extract data
scopus_papers <- scopus_data_raw$df
scopus_affiliations <- scopus_data_raw$affiliation
scopus_authors <- scopus_data_raw$author
# Create file paths
term_for_file <- paste0("scopus_affil_", row_data$affil_id, "_", row_data$date_range)
papers_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/papers/", row_data$date_range, "/", term_for_file, "_papers.csv")
affils_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/affils/", row_data$date_range, "/", term_for_file, "_affils.csv")
authors_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/authors/", row_data$date_range, "/", term_for_file, "_author.csv")
# Write files
suppressMessages({
write_csv(scopus_papers, papers_path)
write_csv(scopus_affiliations, affils_path)
write_csv(scopus_authors, authors_path)
})
return(list(success = TRUE, skipped = FALSE,
term = row_data$affil_id, year = row_data$date_range))
}, error = function(e) {
return(list(success = FALSE, term = row_data$affil_id,
year = row_data$date_range, error = e$message))
})
}
# Run in parallel
results <- future_map(
split(search_df, 1:nrow(search_df)),
~ process_search(.x, api, date_folder_for_files),
.options = furrr_options(seed = TRUE),
.progress = TRUE
)
# Summarize results
successful <- sum(sapply(results, function(x) x$success && !x$skipped))
skipped <- sum(sapply(results, function(x) x$success && x$skipped))
failed <- sum(sapply(results, function(x) !x$success))
cat("\nCompleted:", successful, "successful,", skipped, "skipped (empty),", failed, "failed\n")
# Get failed items
failed_items <- results %>%
keep(~ !.x$success) %>%
map_df(~ tibble(term = .x$term, year = .x$year, error = .x$error))
if (nrow(failed_items) > 0) {
failed_items<-failed_items %>%
rename(date_range=year,
affil_id=term)
cat("\nFailed items:\n")
print(failed_items)
# if cuts out, rerun with these:
new_search_df<-search_df %>%
inner_join(failed_items,by=c("affil_id", "date_range")) %>%
select(affil_id,
date_range) %>%
mutate(row_id=row_number())
}else{
print("Done! No terms failed in the API call.")
}
# Clean up
plan(sequential)
# STEP 4: CHECK ANY UPLOADS OF ALL NOs AFTER INITIAL SEARCHES ----------------------
# after the initial steps, only need to run this step to update. it checks all of them for uploads of every PY
# after the date of the initial three searches.
all_terms<-bind_rows(affils_to_search_all, search_term_over5K) %>%
bind_rows(after_cleanup) %>%
select(affil_id) %>%
distinct()
search_term<-all_terms$affil_id
# search_term<-all_terms$affil_id[580:nrow(all_terms)]
term<-seq_along(search_term)
months <- sprintf("%02d", 1:12)
months<-months[1:2]
# select months since most recent search and present month
#
yr1<- 2020
final_study_yr <- 2025
load_yr<-2026
date_range <- seq(yr1, final_study_yr)
search_df <- expand_grid(search_term, months, load_yr,yr1,final_study_yr) %>%
rename(load_mo = months) %>%
arrange(search_term, load_yr, load_mo) %>%
mutate(row_id = row_number())
# search_df$no_pub<-NA
# row_data<-search_df[1:100,]
# search_df<-new_search_df
plan(multisession, workers = 2) # Use 4 cores, adjust as needed
# Define the processing function
process_search <- function(row_data, api, date_folder_for_files) {
# j <- row_data$row_id
# Progress reporting (will show in each worker)
# if (j %% 12 == 0) {
# cat("Progress: term / month / year :",
# paste(row_data$search_term, row_data$load_mo, row_data$load_yr, row_data$pub_yr, sep = "-"), "\n")
# }
# Calculate dates
start_date <- paste0(row_data$load_yr, row_data$load_mo, "01")
if (row_data$load_mo == "12") {
end_date <- paste0(row_data$load_yr + 1, "01", "02")
} else {
next_month <- sprintf("%02d", as.numeric(row_data$load_mo) + 1)
end_date <- paste0(row_data$load_yr, next_month, "02")
}
# Build query
a <- paste0("(AF-ID('", row_data$search_term, "') AND (DOCTYPE(ar) OR DOCTYPE(re) OR DOCTYPE(ch) OR DOCTYPE(ed) OR DOCTYPE(le) OR DOCTYPE(dp) OR DOCTYPE(no))")
b <- paste0(" AND PUBYEAR > ", row_data$yr1-1, " AND PUBYEAR < ", row_data$final_study_yr+1,"")
c <- paste0(" AND ORIG-LOAD-DATE > ", start_date, " AND ORIG-LOAD-DATE < ", end_date, ")")
query_string <- paste0(a, b, c)
# API call with error handling
tryCatch({
scopus_data <- rscopus::scopus_search(
query_string,
max_count = 8000,
verbose = FALSE,
view = "COMPLETE",
api_key = api
)
scopus_data_raw <- gen_entries_to_df(scopus_data$entries)
# Check if valid data
if (nrow(scopus_data_raw$df) == 1 & ncol(scopus_data_raw$df) == 3) {
return(NULL) # Skip empty results
# row_data$no_pub<-TRUE
}
# Extract data
scopus_papers <- scopus_data_raw$df
scopus_affiliations <- scopus_data_raw$affiliation
scopus_authors <- scopus_data_raw$author
# Create file paths
term_for_file <- paste0("scopus_affil_", row_data$search_term, "_",
row_data$load_yr, "_", row_data$load_mo)
papers_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/papers/", row_data$load_yr, "/", term_for_file, "_papers.csv")
affils_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/affils/", row_data$load_yr, "/", term_for_file, "_affils.csv")
authors_path <- paste0("data_raw/scopus_downloads/", date_folder_for_files,
"/authors/", row_data$load_yr, "/", term_for_file, "_author.csv")
# Write files
write_csv(scopus_papers, papers_path)
write_csv(scopus_affiliations, affils_path)
write_csv(scopus_authors, authors_path)
return(list(success = TRUE, term = row_data$search_term,
month = row_data$load_mo, load_year = row_data$load_yr,
pub_year = row_data$pub_yr))
}, error = function(e) {
return(list(success = FALSE, term = row_data$search_term,
month = row_data$load_mo, year = row_data$load_yr,
pub_year = row_data$pub_yr,
error = e$message))
})
}
# Run in parallel
results <- future_map(
split(search_df, 1:nrow(search_df)),
~ process_search(.x, api, date_folder_for_files),
.options = furrr_options(seed = TRUE),
.progress = TRUE
)
# Summarize results
successful <- sum(sapply(results, function(x) !is.null(x) && x$success))
failed <- sum(sapply(results, function(x) !is.null(x) && !x$success))
cat("\nCompleted:", successful, "successful,", failed, "failed\n")
# Clean up
plan(sequential)
failed<-tibble(row_id=which(sapply(results, function(x) !is.null(x) && !x$success)))
if (nrow(failed) > 0) {
new_search_df<-search_df %>%
filter(row_id%in%failed$row_id) %>%
mutate(row_id = row_number())
cat("\nFailed items:\n")
print(failed)
}else{
print("Done! No terms failed in the API call.")
}
# search_df <- expand_grid(search_term, months)
# month <- seq_along(months)
# scan_year = seq(2017,2025,by=1)
# scan_year_seq = seq_along(scan_year)
yr1 = 2019
yr2 = 2025
date_range <- seq(yr1,yr2)
year <- seq_along(date_range)
check_month = 12
check_year = 2025
for (h in term) {
# for (j in year) {
# for (k in month) {
# Print progress every 250-th value of h
if (h %% 50 == 0) {
# Safely handle if term is indexed by h
cat("Progress — h:", h, "; term:", search_term[h], "\n")
}
start_date <- paste0(check_year,months[check_month], "01",sep="")
if(check_month<12){
end_date <- paste0(check_year,(months[check_month+1]), "02",sep="")
}
if(check_month==12){
end_date <- paste0(check_year+1,months[1], "02",sep="")
}
a <- paste("(AF-ID('", search_term[h], "')", " AND (DOCTYPE(ar) OR DOCTYPE(re) OR DOCTYPE(ch) OR DOCTYPE(ed) OR DOCTYPE(le) OR DOCTYPE(dp) OR DOCTYPE(no))", sep = "")
b <- paste(" AND PUBYEAR AFT ", yr1-1, sep = "")
c<- paste(" AND ORIG-LOAD-DATE > ",start_date,")",sep="")
query_string <- paste0(a, b, c)
# query_string <- paste0(a, c)
scopus_data <- rscopus::scopus_search(query_string,
max_count=8000,
# start = 0,
verbose = FALSE,
view = "COMPLETE",
api_key = api)
scopus_data_raw <- gen_entries_to_df(scopus_data$entries)
if(nrow(scopus_data_raw$df)==1 & ncol(scopus_data_raw$df)==3){
next
}else{
scopus_papers <- scopus_data_raw$df
scopus_papers <- scopus_data_raw$df
scopus_affiliations <- scopus_data_raw$affiliation
scopus_authors <- scopus_data_raw$author
folder_for_files<-paste(date_folder_for_files,"/",check_year,sep="")
term_for_file<-paste("scopus_affil_",search_term[h], "_", start_date, sep = "")
papers <- paste("./data_raw/scopus_downloads/",date_folder_for_files,"/papers/",check_year,"/",term_for_file,"_papers", ".csv", sep = "")
write_csv(scopus_papers, papers)
affils <- paste("./data_raw/scopus_downloads/",date_folder_for_files,"/affils/",check_year,"/",term_for_file,"_affils", ".csv", sep = "")
write_csv(scopus_affiliations, affils)
authors <- paste("./data_raw/scopus_downloads/",date_folder_for_files,"/authors/",check_year,"/",term_for_file,"_author", ".csv", sep = "")
write_csv(scopus_authors, authors)
}
}
########################################################################
# ALT CODE IF PARRALLELIZATION IS NOT AN OPTION, USE THIS: #############
########################################################################
# STEP 1 search initial affiliation IDs by PY ------------------------------
# search_term <- anti_join(affils_to_search_all,search_term_over5K) %>%
# select(-agency_primary)
# # term<-seq_along(search_term)
# yr1=2022
# yr2=2022
# date_range <- seq(yr1,yr2)
# # year <- seq_along(date_range)
#
# search_df<-expand_grid(search_term,date_range) %>%
# arrange(desc(date_range))
# # search_df <-search_df[580:nrow(search_df),]
# run <- seq(nrow(search_df))
# for (j in run) {
#
#
# # Print progress every 250-th value of j
# if (j %% 10 == 0) {
# # Safely handle if term is indexed by h
# cat("Progress:", j, "; term:", search_df[j,1], "\n")
# }
#
# a <- paste("(AF-ID('", search_df[j,1], "')", " AND (DOCTYPE(ar) OR DOCTYPE(re) OR DOCTYPE(ch) OR DOCTYPE(ed) OR DOCTYPE(le) OR DOCTYPE(dp) OR DOCTYPE(no))", sep = "")
#
# b <- paste0(" AND PUBYEAR IS ", search_df[j,2],")")
# # b <- paste(" AND (PUBYEAR AFT 2018)", sep = "")
#
# query_string <- paste0(a, b)
#
#
#
#
# scopus_data <- rscopus::scopus_search(query_string,
# max_count=8000,
# view = "COMPLETE",
# verbose = FALSE,
# api_key = api)
#
#
#
# scopus_data_raw <- gen_entries_to_df(scopus_data$entries)
#
# if(nrow(scopus_data_raw$df)==1 & ncol(scopus_data_raw$df)==3){
# next
# }else{
# scopus_papers <- scopus_data_raw$df
# scopus_affiliations <- scopus_data_raw$affiliation
# scopus_authors <- scopus_data_raw$author
#
#
#
# folder_for_files<-paste0(date_folder_for_files,"/",search_df[j,2])
#
# term_for_file<-paste0("scopus_affil_",search_df[j,1], "_", search_df[j,2])
#
#
# papers <- paste("data_raw/scopus_downloads/",date_folder_for_files,"/papers/",search_df[j,2],"/",term_for_file,"_papers", ".csv", sep = "")
# suppressMessages(readr::write_csv(scopus_papers, papers))
#
# affils <- paste("data_raw/scopus_downloads/",date_folder_for_files,"/affils/",search_df[j,2],"/",term_for_file,"_affils", ".csv", sep = "")
# suppressMessages(readr::write_csv(scopus_affiliations, affils))
#
# authors <- paste("data_raw/scopus_downloads/",date_folder_for_files,"/authors/",search_df[j,2],"/",term_for_file,"_author", ".csv", sep = "")
# suppressMessages(readr::write_csv(scopus_authors, authors))
# }
# }
# STEP 2: search original but >5K by upload month ---------------------------
# In these you need to gather by PY and upload month, starting 3 years BEFORE
# pub_year<-2024
# search_term <-search_term_over5K$affil_id
# term<-seq_along(search_term)
# months <- sprintf("%02d", 1:12)
# month <- seq_along(months)
# search_df <- expand_grid(search_term, months)
# final_study_yr<-2025
# date_range <- seq(pub_year-5,final_study_yr) # this is the date range searching for upload of pubs from that year (5 year prior to publication through end of 2025)
# # year <- seq_along(date_range)
#
# search_df <- expand_grid(search_df, date_range) %>%
# rename(load_mo=months,
# load_yr=date_range) %>%
# arrange(search_term,load_yr,load_mo)
#
# # search_df <-search_df[580:nrow(search_df),]
# run <- seq(nrow(search_df))
#
#
#
# for (j in run) {
#
#
#
# # Print progress every 250-th value of j
# if (j %% 12 == 0) {
# # Safely handle if term is indexed by h
# cat("Progress: term / month / year :", (paste(search_df[j,1],search_df[j,2],search_df[j,3],sep="-")), "\n")
# }
#
#
#
#
# start_date <- paste0(search_df[j,3],search_df[j,2], "01")
# if(search_df[j,2]!="12"){
# end_date <- paste0(search_df[j,3],search_df[j+1,2], "02")
# }
# if(search_df[j,2]=="12"){
# end_date <- paste0(search_df[j,3]+1,"01", "02")
# }
#
#
#
# a <- paste("(AF-ID('", search_df[j,1], "')", " AND (DOCTYPE(ar) OR DOCTYPE(re) OR DOCTYPE(ch) OR DOCTYPE(ed) OR DOCTYPE(le) OR DOCTYPE(dp) OR DOCTYPE(no))", sep = "")
#
# # a <- paste("(AF-ID('", search_term[h], "')", " AND (DOCTYPE(ar))", sep = "")
# b <- paste0(" AND PUBYEAR IS ", pub_year)
# # b <- paste(" AND (PUBYEAR AFT 2018)", sep = "")
#
# c<- paste(" AND ORIG-LOAD-DATE > ",start_date, " AND ORIG-LOAD-DATE < ", end_date,")",sep="")
#
#
# query_string <- paste0(a, b, c)
# # query_string <- paste0(a, c)
#
# scopus_data <- rscopus::scopus_search(query_string,
# max_count=8000,
# # start = 0,
# verbose = FALSE,
# view = "COMPLETE",
# api_key = api)
#
#
#
# scopus_data_raw <- gen_entries_to_df(scopus_data$entries)
#
# if(nrow(scopus_data_raw$df)==1 & ncol(scopus_data_raw$df)==3){
# next
# }else{
# scopus_papers <- scopus_data_raw$df
#
#
# scopus_papers <- scopus_data_raw$df
# scopus_affiliations <- scopus_data_raw$affiliation
# scopus_authors <- scopus_data_raw$author
#
#
# folder_for_files<-paste0(date_folder_for_files,"/",pub_year)
#
# term_for_file<-paste("scopus_affil_",search_df[j,1], "_", search_df[j,3],"_",search_df[j,2], sep = "")
#
#
# papers <- paste("data_raw/scopus_downloads/",date_folder_for_files,"/papers/",pub_year,"/",term_for_file,"_papers", ".csv", sep = "")
# write_csv(scopus_papers, papers)
#
#
#
# affils <- paste("data_raw/scopus_downloads/",date_folder_for_files,"/affils/",pub_year,"/",term_for_file,"_affils", ".csv", sep = "")
# write_csv(scopus_affiliations, affils)
#
#
# authors <- paste("data_raw/scopus_downloads/",date_folder_for_files,"/authors/",pub_year,"/",term_for_file,"_author", ".csv", sep = "")
# write_csv(scopus_authors, authors)
#
# }
# }