繁体   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