R dplyr purrr 将数据帧传递给 pmap_dfr() 时出现错误

问题描述 投票:0回答:1

我正在准备一个函数来绘制三角函数图。我编写了一个函数,当给定单一值 theta 的参数时,该函数成功返回正确的值,但是当我尝试使用 purrr::pmap_dfr() 传递每个参数有一列的数据帧以生成一组值到图表,我收到一个错误,其消息似乎与情况不匹配。

这是一个可重现的示例:

thetas <- seq(from = -3, to = 3, by = 0.05) 
amplitudes <- rep(1, times = length(thetas))
period_denoms<- rep(1, times = length(thetas))
horizontal_shifts <- rep(0, times = length(thetas))
vertical_shifts <- rep(0, times = length(thetas))

argList <- list(thetas,
                amplitudes,
                period_denoms,
                horizontal_shifts,
                vertical_shifts) %>%
    as_tibble(.name_repair = ~ c("theta",
                                "amplitude",
                                "period_denom",
                                "horizontal_shift",
                                "vertical_shift")
                )
xformed_sine <- function(theta, amplitude, period_denom, horizontal_shift, vertical_shift){
        period <- (2 * pi)/abs(period_denom)
        
        return(amplitude * sinpi(period(theta + horizontal_shift)) + vertical_shift)
}

pmap_dfr(argList, xformed_sine)

R 返回此错误:

dplyr::bind_rows()
中的错误: !参数 1 必须是数据框或命名原子向量。”

当我阅读错误时,R 抱怨对象 argList 不是数据框,但当我运行此代码时:

is.data.frame(argList)
返回的值为 TRUE。

最后一位的返回与错误消息不匹配,这告诉我 argList 不是数据帧。两者都不可能是真的,我怀疑要么是我误解了错误消息,要么是 pmap_dfr() 函数中存在错误。

有什么想法吗?

r purrr pmap
1个回答
0
投票

错误指的是 xformed_sine() 函数返回的内容。您可以将其设为小标题,您的代码将运行:

xformed_sine <- function(theta, amplitude, period_denom, horizontal_shift, vertical_shift){
  period <- (2 * pi)/abs(period_denom)
  
  return(
    tibble(result = amplitude * sinpi(period(theta + horizontal_shift)) + vertical_shift)
  )
}

pmap_dfr(argList, xformed_sine)

# A tibble: 121 × 1
   result             
   <Period>           
 1 0S                 
 2 -0.15643446504023S 
 3 -0.309016994374948S
 4 -0.453990499739547S
 5 -0.587785252292474S
 6 -0.707106781186547S
 7 -0.809016994374947S
 8 -0.891006524188368S
 9 -0.951056516295154S
10 -0.987688340595138S
# … with 111 more rows
# ℹ Use `print(n = ...)` to see more rows
© www.soinside.com 2019 - 2024. All rights reserved.