【发布时间】:2021-02-26 09:34:46
【问题描述】:
我想计算以下等式:
使用 dplyr 并生成一个数据框,其中包含一列 x 值、一列 y 值和一列高度值。
我觉得以下应该可行:
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.
所以似乎正在发生的事情是将整个 x 和 y 列添加到峰值 df,而我想要的是第一行的 x 和 y 添加到峰值 df 然后计算函数.然后将第二行的 x 和 y 相加,以此类推。
我已经尝试过 lapply 并尝试进行 tidy 评估,但无法提出可行的方法。任何想法将不胜感激。
【问题讨论】:
-
如果有人试图重新创建它,Ronak Shah 的答案可以正常工作,但您需要确保将“zp”设置为一个愚蠢的大数字以获得合理的可视化。