Skip to content

Instantly share code, notes, and snippets.

@mbjoseph
Created May 21, 2020 17:33
Show Gist options
  • Save mbjoseph/7083b318e79630f197fa0eac16025625 to your computer and use it in GitHub Desktop.
Save mbjoseph/7083b318e79630f197fa0eac16025625 to your computer and use it in GitHub Desktop.
Example of using grouped linear interpolation
library(tidyverse)
library(reshape2)
library(pbapply)
n_samples <- 100
n_wavelength <- 400
wavelengths <- matrix(nrow = n_samples, ncol = n_wavelength)
reflectances <- matrix(nrow = n_samples, ncol = n_wavelength)
for (i in 1:n_samples) {
wavelengths[i, ] <- sort(runif(n_wavelength, min = 1, max = 1000))
reflectances[i, ] <- rnorm(1, sd = .2) +
sin(.005 * wavelengths[i, ]) +
rnorm(n_wavelength, sd = .03)
}
wv_df <- reshape2::melt(wavelengths, varnames = c("sample", "wavelength")) %>%
as_tibble %>%
rename(band_index = wavelength,
wavelength = value)
rf_df <- reshape2::melt(reflectances, varnames = c("sample", "wavelength")) %>%
as_tibble %>%
rename(band_index = wavelength,
reflectance = value)
d <- full_join(wv_df, rf_df)
d
d %>%
ggplot(aes(x = wavelength, y = reflectance, group = sample)) +
geom_path()
wavelength_vals <- seq(min(wavelengths), max(wavelengths),
length.out = n_wavelength)
interpolations <- d %>%
split(.$sample) %>%
pblapply(function(df) {
interpolated_reflectance <- approx(x= df$wavelength,
y = df$reflectance,
xout = wavelength_vals)
tibble(sample = unique(df$sample),
band_index = seq_along(wavelength_vals),
wavelength = interpolated_reflectance$x,
reflectance = interpolated_reflectance$y)
}) %>%
bind_rows
interpolations %>%
ggplot(aes(x = wavelength, y = reflectance, group = sample)) +
geom_path()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment