Skip to content

Instantly share code, notes, and snippets.

View valentinitnelav's full-sized avatar
🏠
Working from home

Valentin Ștefan valentinitnelav

🏠
Working from home
View GitHub Profile
# Converting coordinates from DMS or DdM formats to decimal
# DMS = "degrees minutes seconds"; DdM = "degrees decimal minutes"
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
dg2dec <- function(varb, Dg=NA, Min=NA, Sec=NA, SW.Hemisphere="S|W") {
# Dg=decimal, Min=minutes and Sec=seconds;
# NOTE 1 - if the format is "degrees decimal minutes - DdM" (e.g. 40° 26.767′ N) and not
# "degrees minutes seconds - DMS" (e.g. 40° 26′ 46″ N), then call the function only with
# Dg and Min arguments, like dg2dec(varb, Dg="°", Min="′N").
# Same applies when there is no seconds symbol (e.g. 45°12'7.38).
# Note that one should not use blank spaces in Dg, Min or Sec arguments (will return NA).
# extract long-lat coordinates from a bunch of kmz files
# first unzips the KMZ-s then reads coordinates from each KML with getKMLcoordinates {maptools}
# (worth checking this as well: https://gist.github.com/holstius/6631918 )
library(maptools)
# list the kmz files in a given folder path
KMZs <- list.files(path="Data/kmz-files", pattern="*.kmz", full.names=FALSE)
# unzip each KMZ file and read coordinates with getKMLcoordinates()
# Call library data.table
library(data.table)
# ============================================ #
# Prepare data #
# ============================================ #
# Read your data.
DT <- fread("Hawaii_sites.csv")
# Get only lat-long unique records.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This is an example of plotting a barplot in a pdf device
# Journals usually accept the pdf vector format
# One can also use other vector formats:
# 1) emf() function from “devEMF" package produces Enhanced Metafile (EMF)
# Microsoft Office should recognize EMFs(https://goo.gl/1bxC7G)
# 2) postscript()
# "Microsoft Office is supposed to be able to handle EPS files
# and R postscript files are by default EPS compatible
# function to get first name from a string of names (including the particle e.g. von Frisch)
# strg = a string containing names
# NOTE: The function still needs further testing. Use with care!
get_author_name <- function(strg){
# remove any leading and trailing whitespace
strg <- trimws(strg)
# check if string starts with two "nobiliary" particles
logic_2prtcl <- grepl(pattern = "^van der|^von der", x = strg, perl=TRUE, ignore.case = TRUE)
# function to get the first n words from a string
get_words <- function(strg, n = 3){
# remove any leading and trailing whitespace
strg <- trimws(strg)
# replace all punctuation with space (except apostrophe)
strg <- gsub(pattern = "[^[:alnum:][:space:]']", replacement = ' ', strg, perl=TRUE)
# merge multiple spaces to single space
strg <- gsub(pattern = "(?<=[\\s])\\s*|^\\s+|\\s+$", replacement = "", strg, perl=TRUE)
# take first n elements when splitting by space
strg <- strsplit(strg, split=" ", fixed=TRUE)[[1]][1:n]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This script presents a simple example of plotting using several graphical devices
# For a list of graphical devices offered in R just run ?Devices
# Note that journals usually accept PDF as vector format and TIFF for images
# PDF is the easiest way to use when it comes to creating graphs in vector format.
# Also the EPS (postscript) format is widely accepted by journals.
# For TIFF files, use the "LZW compression" option when saving.
# That will significantly reduce the file size, without adversely affecting the image quality
# (http://esapubs.org/esapubs/preparation.htm#Ill).
# __________ Create data.frame for graticule labels
# use together with graticule of 10 dg step for latitude and 20 dg step for longitude
lbl.Y <- data.frame(lon = rep(c(-175,175), each=17), # 175 dg used to fit latitude labels inside Earth; adjust this value to shift positions of labels
lat = rep(seq(from=80, to=-80, by=-10), times=2))
lbl.Y$dir <- ifelse(lbl.Y$lat == 0, "", ifelse(lbl.Y$lat > 0, "°N", "°S"))
lbl.Y$lbl <- paste0(abs(lbl.Y$lat), lbl.Y$dir)
lbl.X <- data.frame(lon = rep(seq(from=160, to=-160, by=-20), times=2),
lat = rep(c(-85,85), each=17)) # 85 dg used to fit latitude labels inside Earth; adjust this value to shift positions of labels
lbl.X$dir <- ifelse(lbl.X$lon == 0, "", ifelse(lbl.X$lon > 0, "°E", "°W"))
# ======================================================================================
# Create a simple world map in Robinson projection with labeled graticules using ggplot
# ======================================================================================
# Set a working directory with setwd() or work with an RStudio project
# __________ Set libraries
library(rgdal) # for spTransform() & project()
library(ggplot2) # for ggplot()
# ==========================================================================
# This is a simple script for downloading, unzipping and reading a shapefile
# from www.naturalearthdata.com
# ==========================================================================
library(rgdal)
# ~~~~~~~~~~~ Download shapefile from www.naturalearthdata.com ~~~~~~~~~~~ #
# __ Example 1 - download countries data
download.file(url = "http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/ne_110m_admin_0_countries.zip",
destfile = "ne_110m_admin_0_countries.zip")