vorpal
vorpal

Reputation: 320

using map within mutate to iterate over two dataframes

I want to calculate the following equation:

enter image description here

using dplyr and producing a dataframe with a column of x values, a column of y values and a column of height values.

I feel like the following should work:

library(tidyverse)

# create dataframe for xi, yi and hi in equation.
peaks <- tibble(xp = c(0.25, 0.75),
                yp = c(0.25, 0.75),
                zp = c(1000000000000, 1000000000000))

# create dataframe with x and y values equally distributed across a grid
breaks <- 20
n <- (0:breaks)/breaks
expand_grid(x = n, y = n) %>%
  mutate(height = sum(pmap_dbl(tibble(peaks, x = x, y = y), function(xp, yp, zp, x, y){
    zp^(-1*((x - xp)^2 + (y - yp)^2))
  })))

# Error: Problem with `mutate()` input `height`.
# x Tibble columns must have compatible sizes.
# * Size 2: Existing data.
# * Size 441: Column `x`.
# i Only values of size one are recycled.
# i Input `height` is `sum(...)`.
# Run `rlang::last_error()` to see where the error occurred.

So what appears to be happening, is that the whole x and y columns are added to the peaks df, whereas what I want is the x and y of the first row to be added to the peaks df and then the function calculated. And then the x and y of the second row is added, and so on.

I've tried lapply and trying tidy evaluation, but haven't been able to come up with something that works. Any ideas would be appreciated.

Upvotes: 0

Views: 233

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Don't pass peaks in map function, also sum should be inside the map function. Try :

library(tidyverse)

expand_grid(x = n, y = n) %>%
  mutate(height = map2_dbl(x, y, ~{
    sum(with(peaks, zp^(-1*((.x - xp)^2 + (.y - yp)^2))))
  }))

#       x     y height
#   <dbl> <dbl>  <dbl>
# 1     0  0     0.825
# 2     0  0.05  0.878
# 3     0  0.1   0.926
# 4     0  0.15  0.966
# 5     0  0.2   0.997
# 6     0  0.25  1.02 
# 7     0  0.3   1.03 
# 8     0  0.35  1.04 
# 9     0  0.4   1.03 
#10     0  0.45  1.01 
# … with 431 more rows

Upvotes: 2

Related Questions