【问题标题】:dplyr error "length(xmin) == 1 is not TRUE" with mutate when using the integral() functiondplyr 错误 "length(xmin) == 1 is not TRUE" 使用积分()函数时发生变异
【发布时间】:2020-10-14 01:02:22
【问题描述】:

我有一个如下的数据框

lower <- c(1,5,15)
upper <-c(5,15,30)
df<-data.frame(lower,upper)

我想使用 dplyr 的 mutate 来创建一个定义函数曲线下面积的新变量。函数如下。

my_fun <- function(x){y = 1.205016 + 0.03796243 * log(x)}

我正在使用pracma 包中的integral() 函数来查找曲线下的区域。当我在一对上限值和下限值上使用此函数时,它运行时没有错误,如下所示。

integral(my_fun, 1,5)
[1] 4.973705`

但是,当我尝试使用 dplyr 的 mutate 运行相同的功能时,我得到以下信息。

new_df <- df %>%
   mutate(new_variable = integral(my_fun, lower, upper))

积分错误(my_fun, lower, upper) : length(xmin) == 1 is not 是的

似乎integral 函数必须读取整个向量df$lowerdf$upper,而不是读取单个值对1,5。有没有使用 dplyr 的mutate 的解决方案,或者我应该寻找其他解决方案。

我环顾四周,与 mutate 相关的这个错误的唯一实例似乎没有解决我在这里遇到的问题。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以使用rowwise

    library(dplyr)
    library(pracma)
    df %>%
        rowwise %>%
         mutate(new_variable = integral(my_fun, lower, upper))
    

    -输出

    # A tibble: 3 x 3
    # Rowwise: 
    #  lower upper new_variable
    #  <dbl> <dbl>        <dbl>
    #1     1     5         4.97
    #2     5    15        12.9 
    #3    15    30        19.8 
    

    map2

    library(purrr)
    df %>%
         mutate(new_variable = map2_dbl(lower, upper, ~integral(my_fun, .x, .y)))   
    

    -输出

    #  lower upper new_variable
    #1     1     5     4.973705
    #2     5    15    12.907107
    #3    15    30    19.837273
    

    或使用pmap

    df %>%
         mutate(new_variable = pmap_dbl(cur_data(), ~ integral(my_fun, ..1, ..2)))
    #  lower upper new_variable
    #1     1     5     4.973705
    #2     5    15    12.907107
    #3    15    30    19.837273
    

    或使用base R

    df$new_variable <-  unlist(Map(function(x, y) 
              integral(my_fun, x, y), df$lower, df$upper))
    

    或者使用来自base Rapply

    apply(df, 1, function(x) integral(my_fun, x[1], x[2]))
    #[1]  4.973705 12.907107 19.837273
    

    【讨论】:

    • 感谢您的回答。您是否知道可以帮助我理解为什么会出现此错误的资源?我习惯使用 mutate() 和其他函数,之前没有见过这个错误。
    • @Rhizoblaster 你的意思是你的函数错误还是基于我的代码的错误?
    • @Rhizoblaster 如果这是您帖子上显示的错误,那只是该函数没有针对参数进行矢量化。即它只能采用单个较低、较高的值,而不是多个值。因此,它在大于 1 时停止长度检查
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2021-05-26
    • 2021-11-04
    • 2023-03-13
    • 1970-01-01
    • 2011-04-28
    相关资源
    最近更新 更多