Skip to content

Instantly share code, notes, and snippets.

View arcaravaggi's full-sized avatar

Anthony Caravaggi arcaravaggi

View GitHub Profile
@arcaravaggi
arcaravaggi / multidf_to_csv.R
Last active August 15, 2017 14:16
Export all active dataframes to named csv files
# Create labelled list of all active dataframes
my.list <- mget(ls(pattern="*_UMAC"))
# Use write.csv in a for loop, creating files for each and naming
# according to label (i.e. df name)
for (i in seq_along(my.list)){
write.csv(my.list[i], paste(names(my.list)[i], ".csv"), col.names = TRUE)
}
@arcaravaggi
arcaravaggi / df_col_split.R
Last active August 15, 2017 10:45
Split column into multiple based on spaces, extra characters, etc.
# Split column into multiple based on spaces, extra characters, etc.
df <- data.frame(x= c("crust (5)","things (3)","stuff (8)"))
library(tidyr)
df2 <- extract(df, x, into = c("pet", "sampSize"), "([^(]+)\\s+\\(([0-9]+).")
@arcaravaggi
arcaravaggi / arrange_cols.R
Last active August 15, 2017 10:44
Arrange columns of dataframe by position
##arrange df vars by position
# from https://stackoverflow.com/questions/5620885/how-does-one-reorder-columns-in-a-data-frame
##'vars' must be a named vector, e.g. c("var.name"=1)
# e.g.
# table <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))
# arrange.vars(table, c("Out"=2))
# arrange.vars(table, c("Out"=2, "Files"=1, "Time"=4))
arrange.vars <- function(data, vars){
##stop if not a data.frame (but should work for matrices as well)
@arcaravaggi
arcaravaggi / update_migrate.R
Last active July 4, 2024 12:57
Update R and migrate R packages to new installation from within the console
#From https://stackoverflow.com/questions/1401904/painless-way-to-install-a-new-version-of-r
# Run in the old version of R (or via RStudio)
setwd("C:/Temp/")
packages <- installed.packages()[,"Package"]
save(packages, file="Rpackages")
# INSTALL NEW R VERSION
if(!require(installr)) { install.packages("installr"); require(installr)} #load / install+load installr
# See here for more on installr: https://www.r-statistics.com/2013/03/updating-r-from-r-on-windows-using-the-installr-package/
@arcaravaggi
arcaravaggi / multicsv_lst.R
Last active October 3, 2017 13:00
Read multiple csv files from one directory
# Read in all csv files in directory
files <- list.files(pattern = "*.csv")
# Create dfs for each csv then create list
for (i in 1:length(files))
assign(files[i],
read.csv(files[i]))
lst <- mget(ls(pattern = "*.csv"))
@arcaravaggi
arcaravaggi / tweetstorm.R
Created August 31, 2017 11:30
Create a series of tweets from one text string.
# if tweetnow is set to TRUE, sends the tweets directly from R to Twitter
# this function requires installing the rtweet package and setting up the relevant
# Twitter user credentials
# otherwise, the tweetstorm outputs to the console; the user can copy/paste to Twitter manually
#
# From https://sites.tufts.edu/emotiononthebrain/2017/08/12/time-for-a-tweetstorm/
tweetstorm <- function(s, tweetnow = FALSE) {
#if you'll be tweeting directly from R, update the user name and token variables
@arcaravaggi
arcaravaggi / cor.test.R
Created September 14, 2017 15:42
Function for pairwise correlations across a data frame
# E.g. qDat.corr <- as.data.frame(cor.test.p(x))
cor.test.p <- function(x){
FUN <- function(x, y) cor.test(x, y)[["p.value"]]
z <- outer(
colnames(x),
colnames(x),
Vectorize(function(i,j) FUN(x[,i], x[,j]))
)
dimnames(z) <- list(colnames(x), colnames(x))
@arcaravaggi
arcaravaggi / modOverlap.R
Created September 21, 2017 12:59
Metrics for quantifying the similarity among ecological niche models
# The modOverlap function calculates three metrics:
# Shoener’s D for niche overlap
# Hellinger distance between probability distributions
# Warren's I similarity statistic
#
# This function is also found in the fuzzysim package
#
# From https://modtools.wordpress.com/2015/10/30/modoverlap/
modOverlap <- function (pred1, pred2, na.rm = TRUE)
@arcaravaggi
arcaravaggi / coefplot.R
Created September 25, 2017 14:26
Plot regression coefficients
# published on http://www.r-statistics.com/2010/07/visualization-of-regression-coefficients-in-r
# originally written by "<a href="http://statmath.wu.ac.at/~zeileis/">Achim Zeileis</a>"
# GPL-2
#
# E.g. coefplot(glm, parm = -1)
coefplot <- function(object, df = NULL, level = 0.95, parm = NULL,
labels = TRUE, xlab = "Coefficient confidence intervals", ylab = "",
xlim = NULL, ylim = NULL,
las = 1, lwd = 1, lty = c(1, 2), pch = 19, col = 1,
@arcaravaggi
arcaravaggi / spLine.ld.R
Last active October 3, 2017 13:00
Intersects SpatialLine and SpatialPolygon objects and produces total line length and density per polygon ID.
# Calculate total line length and density for a given set of polygons
#
# Intersects SpatialLine and SpatialPolygon objects, calculates individual line length,
# appends to dataframe extracted from intersect object and summarises by polygon ID.
# If density is not required, do not specify area parameter `a`.
#
# The function assumes a spatial projection system where distance is given in metres.
#
# E.g.
# sp1 = object of class SpatialLine/SpatialLineDataFrame