簡體   English   中英

將自定義函數與tidyverse一起使用

[英]Using a custom function with tidyverse

我創建了一個虛擬函數來獲取一個變量的滯后,然后將其與其他tidyverse函數一起使用。 它在我調用mutate之后起作用,但在調用group_by之后卻不起作用。 它將引發以下錯誤: Error in mutate_impl(.data, dots) : Not compatible with STRSXP: [type=NULL].錯誤: Error in mutate_impl(.data, dots) : Not compatible with STRSXP: [type=NULL].

這是一個repex:

#create a function to lag a selected variable
lag_func <- function(df, x) {
  mutate(df, lag = lag(df[,x])) 
}

#works
iris %>% 
  mutate(lead = lead(Petal.Length)) %>%
  lag_func('Petal.Length')

#doesn't work
iris %>%
  group_by(Species) %>%
  mutate(lead = lead(Petal.Length)) %>%
  lag_func('Petal.Length')

知道錯誤的含義和/或如何解決?

將列名作為參數傳遞給tidyverse函數的最佳方法是使用enquo()將其轉換為quosure 參見以下代碼:

lag_func <- function(df, x) {
  x <- enquo(x)
  mutate(df, lag = lag(!!x)) # !! is to evaluate rather than quoting (x)
}

現在讓我們嘗試一下我們的功能:

iris %>%
  group_by(Species) %>%
  mutate(lead = lead(Petal.Length)) %>%
  lag_func(Petal.Length)

# A tibble: 150 x 7
# Groups:   Species [3]
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species  lead   lag
          <dbl>       <dbl>        <dbl>       <dbl> <fct>   <dbl> <dbl>
 1          5.1         3.5          1.4         0.2 setosa    1.4  NA  
 2          4.9         3            1.4         0.2 setosa    1.3   1.4
 3          4.7         3.2          1.3         0.2 setosa    1.5   1.4
 4          4.6         3.1          1.5         0.2 setosa    1.4   1.3
 5          5           3.6          1.4         0.2 setosa    1.7   1.5
 6          5.4         3.9          1.7         0.4 setosa    1.4   1.4
 7          4.6         3.4          1.4         0.3 setosa    1.5   1.7
 8          5           3.4          1.5         0.2 setosa    1.4   1.4
 9          4.4         2.9          1.4         0.2 setosa    1.5   1.5
10          4.9         3.1          1.5         0.1 setosa    1.5   1.4
# ... with 140 more rows

有關如何在自定義函數中使用tidyverse函數的更多信息,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM