【问题标题】:function is not working within pipeline when using mutate使用 mutate 时函数在管道中不起作用
【发布时间】:2023-03-07 19:47:01
【问题描述】:

我的函数在独立的基础上工作,但拒绝在管道中工作。我的语法有问题:

library(tidyverse)


phase1_function <- function(a1, a2, a3, a4) {

  if(any(is.na(a1), is.na(a2), is.na(a3), is.na(a4))){
    return("")  }

  if(a4 < a3){
    if(a3 < a2){
      if(a2 < a1) {"phase_1"}
    } } else {""}


}

# This works
phase1_function(1, 2, 3, NA)
phase1_function(31, 30, 29, 28)



x <- c(1:31)

# This refuses to work
data.frame(x = x) %>% 
  mutate(x1 = Hmisc::Lag(x),
           x2 = Hmisc::Lag(x1),
           x3 = Hmisc::Lag(x2)) %>%

  mutate(x4 = phase1_function(x, x1, x2, x3))

请你帮我看看我的语法

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    当您使用mutate 时,它会在函数中传递整个列,因此它会为整个列返回相同的值。相当于

    phase1_function(c(1, 2), c(2, 1), c(3, 4), c(NA, 1))
    #[1] ""
    

    注意它是如何只返回一个值作为输出的。

    您需要在其中传递值rowwise

    library(tidyverse)
    
    data.frame(x = x) %>% 
       mutate(x1 = Hmisc::Lag(x),
              x2 = Hmisc::Lag(x1),
              x3 = Hmisc::Lag(x2)) %>%
       rowwise() %>%
      mutate(x4 = phase1_function(x, x1, x2, x3))
    
    # A tibble: 31 x 5
    #       x    x1    x2    x3 x4     
    #   <int> <int> <int> <int> <chr>  
    # 1     1    NA    NA    NA ""     
    # 2     2     1    NA    NA ""     
    # 3     3     2     1    NA ""     
    # 4     4     3     2     1 phase_1
    # 5     5     4     3     2 phase_1
    # 6     6     5     4     3 phase_1
    # 7     7     6     5     4 phase_1
    # 8     8     7     6     5 phase_1
    # 9     9     8     7     6 phase_1
    #10    10     9     8     7 phase_1
    # … with 21 more rows
    

    如果你想避免rowwise,另一种选择是使用pmap from purrr

    data.frame(x = x) %>%
       mutate(x1 = Hmisc::Lag(x),
              x2 = Hmisc::Lag(x1),
              x3 = Hmisc::Lag(x2)) %>%
       mutate(x4 = pmap(list(x, x1, x2, x3), phase1_function))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-23
      • 2020-07-30
      • 2019-05-26
      • 1970-01-01
      • 2018-02-02
      • 2017-05-28
      • 1970-01-01
      • 2016-06-02
      相关资源
      最近更新 更多