Repository navigation
Expand file tree
/
Copy pathLPSN_API_functions.R
More file actions
5244 lines (3601 loc) · 109 KB
/
Copy pathLPSN_API_functions.R
File metadata and controls
5244 lines (3601 loc) · 109 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
#' Utilities and functions used in the LPSN Taxonomic correction walkthrough
#'
#' These functions were created by R Gore in April 2026 with some AI help.
#'
#' Use these as needed, however these functions are not being actively maintained,
#' so I highly recommend you use a subset of your taxonomy file in a test run
#' to validate the function is returning the correct and manually
#' checking the results in LPSN. A list of taxa that failed to return a result,
#' is also provided to enable manual searches.
#'
#' How long does it take?
#' The whole process is shorter if you prepare your data, there will be fewer manual searches
#' needed if the data is prepared properly.
#'
#' Are there records that cannot be retrieved?
#' The LPSN API currently does not return Candidatus records, these taxa names can be manually searched
#' using the website and then selecting the parent for each record, working backward to create a lineage.
#'
#' The LPSN API will not retrieve superseded synonyms taxa like Firmicutes. If starting from lower levels,
#' like genus or family, the code works backwards to create a lineage and will not encounter an error.
#' If the search starts at the superseded synonym, it will reject as not found and a manual search is
#' required.
#'
#' 1. Clean your data.
#'
#' 1.1 Remove underscores and any orphaned characters/numbers that result.
#' AGRF often append letter to taxonomy levels to indicate which
#' database the information came from, e.g. Enterococcus A avium, Enterococcus AB avium,
#' Enterococcus AD avium B. Sometimes databases have spurious names that will need to be fixed
#' before the LPSN API call or after the run has finished, e.g. Candidatus Koribacter Koribacter.
#'
#' 1.2 Any solo words should be removed from the species column, e.g. soil, bacterium, rectale, etc.
#' In AGRF files, both the genus and species names populate the species field. Check what is the norm
#' for the specific database you're using.
#'
#' 1.3 Some databases are not able to resolve which closely related genera a sequence
#' belongs to and will provide a concatenated name, e.g. genus
#' Allorhizobium-Neorhizobium-Pararhizobium-Rhizobium, this will be ignored if left as is,
#' and the search will begin at the next highest taxonomic level. You can choose to manually
#' change the name before running it or deal with it afterwards
#'
#' 2. Place holder names from the various databases will be ignored, e.g. Genus CAG0056
#' isn't a real name, so it will be ignored and the next highest valid taxonomic level is used.
#' You may prefer to delete these before the run to reduce the number of API calls that are made
#'
#' 3.To shorten the run, use a list of unique names rather that the same names multiple times in the
#' search list, this will result in fewer API calls and a quicker run
#'
#' After cleaning the data, the API run took just over 4 hours, followed by the manual validation
#' of a subset of results search of rejected taxa
# Remove Taxonomy Level Prefixes ##############################################
# This function cleans a taxonomy data frame by stripping the standard prefixes
# (e.g., "d__", "p__") used to indicate lineage level.
#
# @param tax A data frame or tibble containing taxonomy rank columns.
#
# @return A modified data frame (tibble) with prefixes removed from available
# taxonomic columns.
# @export
#
# @examples
# \dontrun{
# df_clean <- remove_taxa_prefix(df)
# }
#
remove_taxa_prefix <- function(tax) {
library(dplyr)
library(stringr)
# Define expected taxonomy columns and their prefixes
taxa_prefixes <- c(
Domain = "^d__",
Kingdom = "^k__",
Phylum = "^p__",
Class = "^c__",
Order = "^o__",
Family = "^f__",
Genus = "^g__",
Species = "^s__"
)
# Convert to data frame
tax <- base::as.data.frame(tax)
# Identify taxonomy columns that are present
existing_taxa <- base::intersect(
names(taxa_prefixes),
base::names(tax)
)
# Apply prefix removal only to existing columns
if (base::length(existing_taxa) > 0) {
tax <- tax |>
dplyr::mutate(
dplyr::across(
dplyr::all_of(existing_taxa),
~ stringr::str_replace(
.x,
taxa_prefixes[dplyr::cur_column()],
"")
)
)
} else {
base::warning(
"No expected taxonomy columns were found. Returning original data.")
}
# Print final column names
base::message("Final column names:")
base::print(base::names(tax))
return(tax)
}
# # Usage example
# # Remove taxonomy prefixes
#
# tax_clean <- remove_taxa_prefix(tax_df)
#
# ### will also display final column names
#
# # View cleaned taxonomy table
# tax_clean
# Removing database flags appended to taxa lineage ############################
#' Clean Orphaned Letters and Report Changes
#'
#' This function, clean_orphaned_letters(), is designed to remove isolated,
#' short uppercase letter codes (e.g., "A", "BC", "XYZ") from a
#' specified column of a data frame, while preserving a record of
#' exactly which rows were changed and how they were modified.
#'
#' @param df The dataframe to process.
#' @param target_col The name of the column to clean (e.g., "Species").
#' @param max_letters The maximum number of uppercase letters to remove (default 3).
#'
#' @return A list containing the cleaned dataframe and a summary of changes.
clean_orphaned_letters <- function(df, target_col, max_letters = 3) {
# Create the regex pattern for 1 to max_letters uppercase letters
# Regex components:
# (^| ) specifies the start of the string OR a space before the letters.
# [A-Z]{1,3} Matches: one, two or 3 UPPERCASE letters
# ( |$) Requires the letters to be followed by either a space or end of string
pattern <- base::sprintf("(^| )[A-Z]{1,%d}( |$)", max_letters)
# Identify rows that WILL be changed
affected_indices <- base::which(base::grepl(pattern, df[[target_col]]))
# Store original values for the report
original_values <- df[[target_col]][affected_indices]
# Perform the cleaning on the specific column
# Step 1: Replace patterns with space
df[[target_col]] <- base::gsub(pattern, " ", df[[target_col]])
# Step 2: Collapse double spaces and trim
df[[target_col]] <- base::trimws(base::gsub("\\s+", " ", df[[target_col]]))
# Store the new values for the report
cleaned_values <- df[[target_col]][affected_indices]
# Create a comparison table for the user to check
report <- base::data.frame(
Row_Index = affected_indices,
Original = original_values,
Cleaned = cleaned_values,
stringsAsFactors = FALSE
)
base::message(base::sprintf("Cleaning complete. %d rows modified.", base::nrow(report)))
# Return both the dataframe and the report
base::return(base::list(
data = df,
report = report
))
}
## usage example
# # Run the function
# results <- clean_orphaned_letters(df, "Species", max_letters = 3)
#
# # Access the cleaned data
# df_trimmed <- results$data
#
# # Check the changes (shows only the rows that were modified)
# View(results$report)
#
# # Quick look at the top of the report in the console
# head(results$report)
# Detection example
# | Text | Detected? |
# | ----------------- | --------- |
# | `"Bacteria A"` | Yes |
# | `"A Bacteria"` | Yes |
# | `"Bacteria AB"` | Yes |
# | `"Bacteria ABC"` | Yes |
# | `"Bacteria ABCD"` | No |
# | `"Bacteria abc"` | No |
#
# Identify Suspicious Taxonomy Names #########################################
#'
#' This function, find_suspicious_taxa(), identifies potentially problematic
#' taxonomy names within a specified dataframe column. Taxa are flagged based
#' on user-defined quality-control criteria:
#'
#' 1. Presence of numerical characters
#' 2. Fewer than a specified number of alphabetic letters
#' 3. Multiple words within a taxonomy name (optional)
#' Please NOTE: taxa can be prefixed with Candidatus,
#' so the list returned should be checked before taxa names are changed
#'
#' The function is intended as a taxonomy quality-control step after initial
#' cleaning. It does not modify the dataframe. Instead, it returns a report
#' containing suspicious taxonomy names and the criteria responsible for
#' flagging them.
#'
#' @param df The dataframe containing taxonomy information.
#'
#' @param target_col The taxonomy column to inspect
#' (e.g., "Phylum", "Genus", "Species").
#'
#' @param min_letters Minimum number of alphabetic characters required for a
#' taxon name to avoid being flagged (default = 5).
#'
#' @param check_multi_word Logical. Should taxa containing multiple words be
#' flagged? Default = FALSE.
#'
#' @param export_csv Logical. Should the report be exported as a CSV file?
#' Default = FALSE.
#'
#' @param file Filename for CSV output if export_csv = TRUE.
#'
#' @return A list containing:
#'
#' \describe{
#' \item{taxa}{A character vector of suspicious taxonomy names.}
#'
#' \item{report}{A dataframe containing:
#' \itemize{
#' \item Taxon
#' \item Has_Numbers
#' \item Letter_Count
#' \item Word_Count
#' \item Has_Multiple_Words
#' }}
#' }
#'
#' @examples
#'
#' genus_check <- find_suspicious_taxa(
#' df = df_trimmed,
#' target_col = "Genus",
#' min_letters = 6,
#' check_multi_word = TRUE,
#' export_csv = TRUE,
#' file = "genus_suspicious_taxa.csv"
#' )
#'
#' genus_check$report
#'
#'
#' #' phylum_check <- find_suspicious_taxa(
#' df = tax_df,
#' target_col = "Phylum",
#' check_multi_word = TRUE
#' )
#'
#' phylum_check$report
#'
#'
#' @importFrom stringr str_detect str_count str_remove_all
#' @importFrom dplyr arrange desc
#' @export
#' @importFrom stringr str_detect str_count str_remove_all str_squish
#' @importFrom dplyr arrange desc
#' @export
find_suspicious_taxa <- function(
df,
target_col,
min_letters = 5,
check_multi_word = FALSE,
export_csv = FALSE,
file = NULL
) {
# Validate inputs
if (!base::is.data.frame(df)) {
stop("'df' must be a dataframe.")
}
if (!target_col %in% base::names(df)) {
stop(base::sprintf("Column '%s' not found.", target_col))
}
# Extract unique taxa
taxa <- unique(df[[target_col]])
taxa <- taxa[!is.na(taxa)]
# Calculate QC features
has_numbers <- stringr::str_detect(taxa, "\\d")
letter_count <- stringr::str_count(
stringr::str_remove_all(taxa, "[^A-Za-z]")
)
word_count <- stringr::str_count(
stringr::str_squish(taxa), "\\S+"
)
has_multi_word <- word_count > 1
# Apply QC rules
suspicious <-
has_numbers |
letter_count < min_letters
# Add multi-word rule if requested
if (isTRUE(check_multi_word)) {
suspicious <- suspicious |
has_multi_word
}
# Create report
report <- data.frame(
Taxon = taxa[suspicious],
Has_Numbers = has_numbers[suspicious],
Letter_Count = letter_count[suspicious],
Word_Count = word_count[suspicious],
Has_Multiple_Words = has_multi_word[suspicious],
stringsAsFactors = FALSE
)
if (nrow(report) > 0) {
report <- report |>
dplyr::arrange(
dplyr::desc(Has_Numbers),
dplyr::desc(Has_Multiple_Words),
Letter_Count,
Taxon
)
}
# Optional export
if (isTRUE(export_csv)) {
if (is.null(file)) {
file <- paste0(target_col, "_suspicious_taxa.csv")
}
utils::write.csv(
report,
file = file,
row.names = FALSE
)
}
# output message
message(
sprintf(
"%d suspicious unique taxa identified in '%s'.",
nrow(report),
target_col)
)
return(
list(
taxa = report$Taxon,
report = report
)
)
}
# Usage example
#
# genus_check <- find_suspicious_taxa(
# df = df_trimmed,
# target_col = "Genus",
# min_letters = 6,
# check_multi_word = TRUE, # set to FALSE for sp and maybe genus
# export_csv = TRUE,
# file = "genus_suspicious_taxa.csv"
# )
# Clean Taxonomy Names with Change Log ########################################
#' This function recodes taxonomy names within one or multiple dataframe
#' columns using user-defined replacement mappings. It accepts either a single
#' named character vector for one column or a named list of vectors for
#' multiple columns.
#'
#' The function returns the updated dataframe and a log showing which
#' taxonomy names were changed.
#'
#' @param df The dataframe containing taxonomy information.
#'
#' @param mappings A named character vector for a single column, or a named
#' list of named character vectors for multiple columns.
#'
#' For a single column:
#' \code{c("Old_name" = "New_name")}
#'
#' For multiple columns:
#' \code{list(Column_name = c("Old_name" = "New_name"))}
#'
#' @param column Character string giving the target column when supplying
#' a single mapping vector. Ignored when \code{mappings} is supplied as a
#' named list.
#'
#' @return A list containing:
#' \describe{
#' \item{data}{The dataframe containing updated taxonomy names.}
#'
#' \item{report}{A dataframe containing:
#' \itemize{
#' \item Column: taxonomy column modified
#' \item Original: original taxonomy name
#' \item Updated: replacement taxonomy name
#' }}
#' }
#'
#' @examples
#'
#' # Single column example
#'
#' phylum_mapping <- c(
#' "Bacteroidetes" = "Bacteroidota",
#' "Firmicutes" = "Bacillota"
#' )
#'
#' result <- clean_taxonomy_with_log(
#' df = tax_df,
#' mappings = phylum_mapping,
#' column = "Phylum"
#' )
#'
#'
#' # Multiple column example
#'
#' taxonomy_mappings <- list(
#' Phylum = c(
#' "Bacteroidetes" = "Bacteroidota"
#' ),
#' Genus = c(
#' "Lactobacillus" = "Lacticaseibacillus"
#' )
#' )
#'
#' result <- clean_taxonomy_with_log(
#' df = tax_df,
#' mappings = taxonomy_mappings
#' )
#'
#' @importFrom dplyr recode bind_rows distinct
#' @export
clean_taxonomy_with_log <- function(
df,
mappings,
column = NULL
) {
# Validate dataframe
if (!base::is.data.frame(df)) {
stop("'df' must be a dataframe.")
}
# Validate mappings
if (base::is.atomic(mappings)) {
if (!base::is.character(mappings) ||
base::is.null(base::names(mappings))) {
stop(
"'mappings' must be either a named character vector ",
"or a named list of named character vectors."
)
}
if (base::is.null(column)) {
stop(
"Argument 'column' must be supplied when using ",
"a single mapping vector."
)
}
mappings <- list(
.single_column = mappings
)
single_column <- TRUE
} else if (base::is.list(mappings)) {
if (base::is.null(base::names(mappings))) {
stop(
"'mappings' must be a named list."
)
}
invalid_mapping <- base::vapply(
mappings,
function(x) {
!base::is.character(x) ||
base::is.null(base::names(x))
},
logical(1)
)
if (base::any(invalid_mapping)) {
stop(
"Each element of 'mappings' must be a ",
"named character vector."
)
}
single_column <- FALSE
} else {
stop(
"'mappings' must be either a named character vector ",
"or a named list of named character vectors."
)
}
# Store output and change log
out <- df
change_log <- list()
# Loop through columns
for (col_name in base::names(mappings)) {
# Handle single-column input
if (single_column) {
target_col <- column
} else {
target_col <- col_name
}
# Check column exists
if (!target_col %in% base::names(out)) {
warning(
base::sprintf(
"Column '%s' not found. Skipping.",
target_col
)
)
next
}
# Store original values
old_vals <- out[[target_col]]
# Apply replacements
out[[target_col]] <- dplyr::recode(
out[[target_col]],
!!!mappings[[col_name]]
)
# Identify changes
new_vals <- out[[target_col]]
changed <- !base::is.na(old_vals) &
old_vals != new_vals
if (base::any(changed)) {
change_log[[target_col]] <- base::data.frame(
Column = target_col,
Original = old_vals[changed],
Updated = new_vals[changed],
stringsAsFactors = FALSE
)
}
base::message(
base::sprintf(
"Column [%s]: %d names updated.",
target_col,
base::sum(changed)
)
)
}
# Combine reports
if (base::length(change_log) > 0) {
report <- dplyr::bind_rows(change_log) |>
dplyr::distinct()
} else {
report <- base::data.frame(
Column = character(),
Original = character(),
Updated = character(),
stringsAsFactors = FALSE
)
}
# Return
return(
list(
data = out,
report = report
)
)
}
# ### usage examples
# ### Single column to update
#
# result <- clean_taxonomy_with_log(
# df = df_trimmed,
# mappings = genus_map,
# column = "Genus"
# )
#
# genus_clean <- result$data
#
# result$report
#
# ### Multiple columns to update
#
# taxonomy_maps <- list(
#
# Phylum = c(
# "Bacteroidetes" = "Bacteroidota"
# ),
#
# Genus = c(
# "Lactobacillus" = "Lacticaseibacillus",
# "Clostridium" = "Clostridioides"
# )
#
# )
#
#
# result <- clean_taxonomy_with_log(
# df = df_trimmed,
# mappings = taxonomy_maps
# )
# Compare Two Vectors Side-by-Side ###############################################################################
#' Compare Two Vectors Side-by-Side
#'
#' This is useful for checking if your "before and after" lists match
#' up after a filtering step or name changes
#' Takes two vectors of potentially different lengths, displays their
#' length ratio, and aligns them into a single data frame for easy comparison.
#'
#' @param vec1 The first (original) vector.
#' @param vec2 The second (updated) vector.
#'
#' @return A data frame with two columns: 'Original' and 'Updated'.
#' The shorter vector is padded with NAs to match the longer one.
#' @export
#'
compare_vectors <- function(vec1, vec2) {
# Print the length comparison in X:Y format
base::cat(base::length(vec1), ":", base::length(vec2), sep = "", "\n\n")
# Equalise lengths to the maximum found to prevent recycling errors
max_len <- base::max(base::length(vec1), base::length(vec2))
v1_aligned <- vec1
base::length(v1_aligned) <- max_len
v2_aligned <- vec2
base::length(v2_aligned) <- max_len
# Create the data frame to inspect the vectors
df <- base::data.frame(
Original = v1_aligned,
Updated = v2_aligned,
stringsAsFactors = FALSE
)
return(df)
}
# Example usage
# phylum_comparison <- compare_vectors(phylum_list, phylum_list_uptd)
#
## To view the new list
# print(phylum_comparison)
# Process Taxonomy Lookup and Metadata Appending ###############################################################################
#' application of lineage retrieved from LPSN API to original taxonomy file
#'
#'
#' Prerequisites:
#' This function requires the 'openxlsx' package for reading master Excel files.
#' install.packages("openxlsx")
#'
#' Input Requirements:
#' 1. Master Data: Must contain a 'search_term' column used as the lookup key.
#' 2. Taxonomy Data: A CSV where the first column is the ASV/OTU ID.
#' Process Taxonomy Lookup and Metadata Appending
#'
#' This R function takes a taxonomy file and cross-references it against a master
#' reference file that is the result of the API calls to the LPSN database. It searches through
#' specified taxonomic ranks (e.g., Species, Genus) until it finds a match in the master list,
#' then appends the corresponding data. It will produce a file with the ASV_IDs,
#' the original taxonomy, the field that found a match in the LPSN database and the lineage
#' returned from LPSN
#'
#' @param master_path String. Path to the master reference file (.csv, .xlsx, or .xls).
#' Must contain a 'search_term' column.
#' @param taxonomy_path String. Path to the input taxonomy CSV file.
#' @param output_path String. Path where the resulting CSV will be saved.
#' @param check_ranks Character vector. The column names in the taxonomy file to
#' search through, ordered by priority (usually specific to general).
#' @param append_cols Character vector. The columns from the master file to
#' append to the results.
#'
#' @return Writes a CSV file to the specified \code{output_path} and prints a success message.
#' @export
#'
#' @examples
#' \dontrun{
#' ### Define file paths
#' master_file <- "LPSN_result_Master.xlsx"
#' tax_file <- "orifinal_taxonomy.csv"
#' result_file <- "Final_Taxonomy_Matched.csv"
#'
#' ### Define Custom Ranks/Columns (Optional)
#' ### LPSN returns kingdom but you do not need to append it to your file
#' # You can provide these in any case (lower, UPPER, Sentence)
#' # ranks in original taxonomy to check
#' my_check_ranks <- c("species", "genus", "family", "order", "class", "phylum", "kingdom")
#' # columns from LPSN results to append to your file
#' my_append_cols <- c("Domain", "Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species")
#
#' #Run the Function ---
#' process_taxonomy_lookup(
#' master_path = master_file,
#' taxonomy_path = tax_file,
#' output_path = result_file,
#' check_ranks = my_check_ranks,
#' append_cols = my_append_cols
#' )
#' }
#'
process_taxonomy_lookup <- function(master_path,
taxonomy_path,
output_path,
check_ranks = c("Species", "Genus",
"Family", "Order",
"Class", "Phylum",
"Kingdom"),
append_cols = c("domain", "kingdom",
"phylum", "class",
"order", "family",
"genus", "species")) {
# Load Master Data based on file extension
# Detects file extension to use the correct loading function
ext <- base::tolower(tools::file_ext(master_path))
if (ext == "csv") {
master <- utils::read.csv(master_path, stringsAsFactors = FALSE, check.names = FALSE)
} else if (ext %in% c("xlsx", "xls")) {
master <- openxlsx::read.xlsx(master_path)
} else {
base::stop("Master file must be .csv, .xlsx, or .xls")
}
# Load Taxonomy Data
# Loads the target file; assumes the first column is the row identifier
taxonomy <- utils::read.csv(taxonomy_path, row.names = 1, check.names = FALSE, stringsAsFactors = FALSE)
# Column Mapping: case-insensitive
# This section ensures that even if columns are named "genus" vs "Genus", they are found.
# Map check_ranks to actual taxonomy column names
actual_tax_cols <- base::colnames(taxonomy)
mapped_check_ranks <- base::character()
for (r in check_ranks) {
idx <- base::grep(base::paste0("^", r, "$"), actual_tax_cols, ignore.case = TRUE)
if (base::length(idx) > 0) mapped_check_ranks <- base::c(mapped_check_ranks, actual_tax_cols[idx])
}
# Map append_cols to actual master column names
actual_master_cols <- base::colnames(master)
mapped_append_cols <- base::character()
for (c in append_cols) {
idx <- base::grep(base::paste0("^", c, "$"), actual_master_cols, ignore.case = TRUE)
if (base::length(idx) > 0) mapped_append_cols <- base::c(mapped_append_cols, actual_master_cols[idx])
}
# Initialize Result Columns
# Create a column to track which rank/term was successfully matched
taxonomy$matched_search_term <- "none"
for (col in mapped_append_cols) {
taxonomy[[base::paste0("master_", col)]] <- NA_character_
}
# Row-wise Processing
# Iterate through every row of the taxonomy file
# If a match isn't found at the Species level, it moves to Genus, then Family,
# and so on. This maximizes the amount of data recovered.
for (i in 1:base::nrow(taxonomy)) {
# Check each rank (Species, then Genus, etc.) sequentially
for (rank in mapped_check_ranks) {
current_value <- base::as.character(taxonomy[i, rank])
# Skip if the rank is empty or explicitly labeled 'unclassified'
if (base::is.na(current_value) || current_value == "" || base::tolower(current_value) == "unclassified") {
next
}
# Perform case-insensitive search against the master 'search_term' column
match_idx <- base::which(base::tolower(master$search_term) == base::tolower(current_value))
if (base::length(match_idx) > 0) {
first_match <- match_idx[1] # Explicitly take the first hit
taxonomy$matched_search_term[i] <- current_value
# Copy values from Master to Taxonomy for all requested columns
for (m_col in mapped_append_cols) {
taxonomy[i, base::paste0("master_", m_col)] <- master[first_match, m_col]
}
# Once a match is found for a row, stop checking broader ranks
break
}
}
}
# Export
utils::write.csv(taxonomy, output_path, row.names = TRUE)
base::cat(base::sprintf("Done. Results in: %s\n", output_path))
}
# Log your session details to a .csv ################################################################################
log_session <- function(folder_path) {
# Create filename with date: "session_log_20240522.csv"
date_stamp <- format(Sys.Date(), "%Y%m%d")
full_path <- file.path(folder_path, paste0("session_log_", date_stamp, ".csv"))
# Collect Platform and Package info
platform <- sessioninfo::platform_info()
plat_string <- paste0("R ", platform$version, " on ", platform$os)
full_log <- sessioninfo::package_info() |>
as.data.frame() |>
dplyr::select(package, version = loadedversion, source) |>
dplyr::mutate(
run_timestamp = Sys.time(),
platform = plat_string
)
# Append to CSV (header only if file is new)