【问题标题】:using map within mutate to iterate over two dataframes在 mutate 中使用 map 来迭代两个数据帧
【发布时间】: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”设置为一个愚蠢的大数字以获得合理的可视化。

标签: r dplyr purrr


【解决方案1】:

不要在map 函数中传递peakssum 也应该在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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2019-08-28
    相关资源
    最近更新 更多