Average of multiple curves

This R script is useful for creating average curves of experimental material property data. it simply breaks the multiple curve data into discrete chunks and averages the values within each chunk. The size of the window is customizable. Additionally, it also generates a lowess fit for the resultant dataset, applying additional smoothing if desired.

# R Script to compute an average curve from material test data
options(digits = 5)

# Read raw data (data should be in 2 colums) and sort by x-value.
# Data should be offset to the origin and all but a single 0,0 point should be included)
Data <- read.csv("Z:/Christopher/15/141531/Materials/Planar_23.csv", header=FALSE)
Data.sort <- Data[order(Data$V1),]

# Define the number of samples to generate
points <- 19
samples <- floor((length(Data.sort$V1)-1)/points)

# Initialize the matrix (we assume that the )
Result <- matrix(nrow = points, ncol = 2)
Result[1,] <- c(0,0)

# Loop over the data computing the average of groups of data points
# defined by the width of the sample window
i <- 1
x <- 1
for(x in 2:points){
V1 <- V2 <- 0.0
for(y in 1:samples){
V1 <- V1 + Data.sort[y+i,1]
V2 <- V2 + Data.sort[y+i,2]
Result[x,] <- c(V1/samples,V2/samples)

# Plot the raw data and the averaged curve in red
plot(Data.sort, pch = 1)
lines(Result, col = "red", lwd = 3)

# Create a lowess smoothed curve and plot in blue.
# This is helpful to remove noise in the average especially with a
# large number of sampled points
Smooth <- (lowess(Result, f = .3))
lines(Smooth, col = "blue", lwd = 3)

# Perform some data manipulation and export as tab delimited text files
Smooth<-(do.call(rbind, lapply(Smooth, unlist)))
Smooth[,1] <- c(0,0)
write(t(Result), file = "Planar_23_avg.txt", ncolumns = 2, sep = "\t")
write(Smooth, file = "Planar_23_smth.txt", ncolumns = 2, sep = "\t")


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>