[英]Using a custom function with tidyverse
I created a dummy function to get the lag of one variable and I want to use it with other tidyverse
functions. 我创建了一个虚拟函数来获取一个变量的滞后,然后将其与其他
tidyverse
函数一起使用。 It works after I call mutate
but not after calling group_by
. 它在我调用
mutate
之后起作用,但在调用group_by
之后却不起作用。 It throws the following error: Error in mutate_impl(.data, dots) : Not compatible with STRSXP: [type=NULL].
它将引发以下错误:
Error in mutate_impl(.data, dots) : Not compatible with STRSXP: [type=NULL].
错误: Error in mutate_impl(.data, dots) : Not compatible with STRSXP: [type=NULL].
Here is a repex: 这是一个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')
Any idea what the error means and/or how to fix it? 知道错误的含义和/或如何解决?
The best way to pass a column name as an argument to a tidyverse
function is convert it to quosure
using enquo()
. 将列名作为参数传递给
tidyverse
函数的最佳方法是使用enquo()
将其转换为quosure
。 See this code: 参见以下代码:
lag_func <- function(df, x) {
x <- enquo(x)
mutate(df, lag = lag(!!x)) # !! is to evaluate rather than quoting (x)
}
Now let's try our function: 现在让我们尝试一下我们的功能:
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
For more info on how to use tidyverse
functions within your custom functions see here 有关如何在自定义函数中使用
tidyverse
函数的更多信息,请参见此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.