I've written a function to find and save the first derivative to a png file. It takes a data.frame input and a name input and applies this to filter()
and creates the PNG name using paste0
then calculates and saves the first derivative.
I need to apply this A LOT of times, Is there a way to apply it quickly to a vector of names? So far I've been using a hacky way, involving Excel to quickly paste down multiple columns and then merge them together, but I feel like there should be a nice way in R. I've made the data an external input for this example but as its all running off one data frame, I have just been including the data input within the actual function so that the only external input is the name... if that makes sense.
The function:
first_deriv <- function(data, site_name) {
require(pspline)
require(dplyr)
png_name <- paste0(site_name, ".png")
data <- data %>%
filter(site == site_name) %>%
select(age, depth)
age <- data %>% pull(age)
depth <- data %>% pull(depth)
predict <- predict(sm.spline(x = depth, y = age), depth, 1)
png(filename = png_name,
width = 600,
height = 350)
plot(predict, main = site_name, xlab = "depth")
dev.off()
}
Data example:
df <- structure(list(site = c("4NT", "4NT", "4NT", "4NT", "4NT", "10T",
"10T", "10T", "10T", "10T", "5T", "5T", "5T", "5T", "5T"), age = c(-62.1,
-59.7, -57.3, -54.9, -52.5, -62.4, -61.4, -60.4, -59.4, -58.4,
-62.3, -61.2, -60.1, -59, -57.9), depth = c(1, 2, 3, 4, 5, 1,
2, 3, 4, 5, 1, 2, 3, 4, 5)), row.names = c(NA, -15L), class = "data.frame")
names <- c("10t", "4NT", "5T")
How it currently runs:
first_deriv(df, "10T")
first_deriv(df, "4NT")
first_deriv(df, "5T")
Cheers, Paul.