############################ ### Peak Search Function ### ############################ peaks <- function (series, span = 3, ties.method = "first") { if ((span <- as.integer(span))%%2 != 1) stop("'span' must be odd") z <- embed(series, span) s <- span%/%2 v <- max.col(z, ties.method = ties.method) == 1 + s pad <- rep(FALSE, s) result <- c(pad, v, pad) result } #### Peak Search Function Usage # Create an extra column in the dataframe 'df', called 'peaks' containing # either 'TRUE' or 'FALSE' depending on whether the value on any given row of 'temp' # is a peak (based on a span of 3) df$peaks <- peaks(df$temp, 3) # Extract all rows where the value of 'temp' was a peak to a new dataframe 'dfpeaks' dfpeaks <- subset(df, peaks=='TRUE') ############################ ### Linear Interpolation ### ############################ # This code assumes that 'df' is a dataframe containing 2 columns, 'time' & 'temp'. # 'time' is assumed to be standardised to 'time since trap shut'. # 'temp' is assumed to be standardised to temperature difference from baseline. # Load Required Packages require("zoo") require(ggplot2) require(Hmisc) # Set Up Required Zoo Object to Data Frame Conversion Function zoo.to.data.frame <- function(x, index.name="datetime") { stopifnot(is.zoo(x)) xn <- if(is.null(dim(x))) deparse(substitute(x)) else colnames(x) setNames(data.frame(index(x), x, row.names=NULL), c(index.name,xn)) } # Convert Dataframe to Zoo Object dfzoo <- zoo(df) # Make Relative Time Column Index for na.approx index(dfzoo) <- dfzoo[,1] # Interpolate Sequence of Temps for 0-120 sec, giving a single value for each second dfzoo.interpolated <- na.approx(object=bleeding1.zoo.for.interp, xout=seq(from=0, to=120, by=1)) # Convert Zoo Object back to Dataframe dfzoo.interpolated.df <- zoo.to.data.frame(dfzoo.interpolated) ################# ### Mean Plot ### ################# # This code assumes that all interpolated dataframes have been joined into a single # dataframe 'df' containing 3 columns, 'time', 'temp', and 'test' (with 'test' indicating # the identity of each individual temperature response curve) ggplot(df,aes(x=time,y=temp)) + stat_summary(fun.data ="mean_cl_boot", mult=1, geom = "smooth", colour="red")