在 mutate 中使用 map 迭代两个数据帧
using map within mutate to iterate over two dataframes
我想计算以下等式:
使用 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 并尝试进行整洁的评估,但一直无法想出有效的方法。任何想法将不胜感激。
不要在map
函数中传递peaks
,sum
也应该在map
函数中。尝试:
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
我想计算以下等式:
使用 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 并尝试进行整洁的评估,但一直无法想出有效的方法。任何想法将不胜感激。
不要在map
函数中传递peaks
,sum
也应该在map
函数中。尝试:
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