boshek
boshek

Reputation: 4416

Finding interpolations by group, maybe using dplyr

I am looking to use the interp and interp2xyz functions from akima in a dplyr pipe as I would like to calculate the interpolation by a group variable and output the xyz values AND a grouping variable. So I ideally I'd like something like this (a general solution):

DATFRAME %>%
group_by(GROUPING VARIABLE) %>%
summarise(interp(x, y , z))

So it is relatively simple to calculate some interpolation values on the whole dataframe and then create another dataframe that has those values using the interpolation functions from the akima package:

library(dplyr)
library(akima)

df <- data.frame(
  x=runif(200, 0, 5),
  y=runif(200, 0, 5),
  z=runif(200, 1, 2),
  Group=LETTERS[seq( from = 1, to = 2 )])

interp_df <- interp(x=df$x, y=df$y, z=df$z)

interp2xyz(interp_df, data.frame=TRUE)

But when I try to incorporate those into a dplyr pipe setup like so:

df %>%
  group_by(Group) %>%
  summarise(interp(x=x, y=y, z=z))

Error: expecting a single value

Or then maybe using mutate:

df %>%
  group_by(Group) %>%
  mutate(interp(x=x, y=y, z=z))

Error: incompatible size (3), expecting 100 (the group size) or 1

I am not married to the dplyr solution - that is just the approach I can think of. Does anyone know of a way to calculate a 3D interpolation by a grouping variable such that a dataframe with all groups and their interpolations is the result?

Upvotes: 2

Views: 252

Answers (1)

hrbrmstr
hrbrmstr

Reputation: 78832

There is no try, only do():

dpinterp <- function(df) {
  interp_df <- interp(x=df$x, y=df$y, z=df$z)
  interp2xyz(interp_df, data.frame=TRUE)
}

df %>%
  group_by(Group) %>%
  do(dpinterp(.))

Upvotes: 4

Related Questions