-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfinbif_check_taxa.R
117 lines (77 loc) · 2.28 KB
/
finbif_check_taxa.R
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
#' Check FinBIF taxa
#'
#' Check that taxa are in the FinBIF database.
#'
#' @aliases fb_check_taxa
#'
#' @param taxa Character (or list of named character) vector(s). If a list each
#' vector can have the name of a taxonomic rank (genus, species, etc.,).
#' The elements of the vectors should be the taxa to check.
#' @param cache Logical or Integer. If `TRUE` or a number greater than zero,
#' then data-caching will be used. If not logical then cache will be
#' invalidated after the number of hours indicated by the argument.
#' @return An object of class `finbif_taxa`. A list with the same form as
#' `taxa`.
#' @examples \dontrun{
#'
#' # Check a scientific name
#' finbif_check_taxa("Cygnus cygnus")
#'
#' # Check a common name
#' finbif_check_taxa("Whooper swan")
#'
#' # Check a genus
#' finbif_check_taxa("Cygnus")
#'
#' # Check a list of taxa
#' finbif_check_taxa(
#' list(
#' species = c("Cygnus cygnus", "Ursus arctos"),
#' genus = "Betula"
#' )
#' )
#' }
#' @export
finbif_check_taxa <- function(
taxa,
cache = getOption("finbif_use_cache")
) {
taxa_list <- as.list(taxa)
taxa_list_names <- names(taxa_list)
taxa_list_names <- tolower(taxa_list_names)
has_names <- length(taxa_list_names) > 0L
for (i in seq_along(taxa_list)) {
taxa_list_name <- character()
if (has_names) {
taxa_list_name <- taxa_list_names[[i]]
}
taxa_list_name_length <- length(taxa_list_name)
no_name <- identical(taxa_list_name_length, 0L)
taxa_i <- taxa_list[[i]]
taxa_names <- taxa_i
for (j in seq_along(taxa_i)) {
id <- NA_character_
taxon <- taxa_i[[j]]
resp <- finbif_taxa(taxon, cache = cache)
if (length(resp[["content"]]) > 0L) {
content <- resp[["content"]][[1L]]
check_rank_obj <- list(name = taxa_list_name, rank = content)
if (no_name || check_rank(check_rank_obj)) {
id <- content[["id"]]
}
}
taxa_i[[j]] <- id
}
names(taxa_i) <- taxa_names
taxa_list[[i]] <- taxa_i
}
if (has_names) {
names(taxa_list) <- taxa_list_names
}
structure(taxa_list, class = c("list", "finbif_taxa_list"))
}
#' @noRd
check_rank <- function(obj) {
rank <- sub("MX.", "", obj[[c("rank", "taxonRank")]])
identical(obj[["name"]], rank)
}