R/get_inat_obs_user.R

Defines functions get_inat_obs_user

Documented in get_inat_obs_user

#' Download observations for a user
#' 
#' @description Get all the observations of a specific iNaturalist user.
#' @param username username of the iNaturalist user to fetch records
#' @param maxresults the maximum number of results to return
#' @return a list with full details on a given record
#' @examples \dontrun{
#'   m_obs <- get_inat_obs(query="Monarch Butterfly")
#'   get_inat_obs_user(as.character(m_obs$user_login[1]))
#' }
#' @import httr jsonlite
#' @importFrom utils read.csv
#' @importFrom curl has_internet
#' @export


get_inat_obs_user <- function(username, maxresults = 100){
  
  # check Internet connection
  if (!curl::has_internet()) {
    message("No Internet connection.")
    return(invisible(NULL))
  }
  
  base_url <- "http://www.inaturalist.org/"
  # check that iNat can be reached
  if (httr::http_error(base_url)) { # TRUE: 400 or above
    message("iNaturalist API is unavailable.")
    return(invisible(NULL))
  }
  
  q_path <- paste0(username, ".csv")
  ping_path <- paste0(username, ".json")
  
  ping_query <- "&per_page=1&page=1"
  ### Make the first ping to the server to get the number of results
  ### easier to pull down if you make the query in json, but easier to arrange results
  ### that come down in CSV format
  ping <-  GET(base_url, path = paste0("observations/", ping_path), query = ping_query)
  total_res <- as.numeric(ping$headers$`x-total-entries`)
  
  if(total_res == 0){
    stop("Your search returned zero results. Perhaps your user does not exist.")
  }
  page_query <-"&per_page=200&page=1"
  dat <-  GET(base_url, path = paste0("observations/", q_path), query = page_query)
  data_out <- read.csv(textConnection(content(dat, as = "text")))
  if(maxresults > 200){
    for(i in 2:ceiling(total_res/200)){
      page_query <- paste0("&per_page=200&page=", i)
      dat <-  GET(base_url, path = paste0("observations/", q_path), query = page_query)
      data_out <- rbind(data_out, read.csv(textConnection(content(dat, as = "text"))))
    }
    
  }
  
  if(maxresults < dim(data_out)[1]){
    data_out <- data_out[1:maxresults,]
  }
  
  return(data_out)
}

Try the rinat package in your browser

Any scripts or data that you put into this service are public.

rinat documentation built on June 14, 2022, 9:06 a.m.