简体   繁体   English

将参数传递给 dplyr 切片

[英]passing argument to dplyr slice

I want to use slice to get the maximum value and the position (to get the date) over a large data.frame and I want to do it for several variables.我想使用 slice 来获取最大值和 position (获取日期)在一个大的data.frame上,我想为几个变量做这件事。 So, I am writing a custom function to pass several variables as argument, but it's not working.所以,我正在编写一个自定义 function 来传递几个变量作为参数,但它不起作用。

           mvar <- "WD"
          
           peak_max <- dataf%>%group_by(year=format(date,"%Y"))%>%
                   dplyr::slice(which.max(!!mvar))
          

I used summarise, but it also failed when passing the argument:我使用了总结,但在传递参数时它也失败了:

            peak_max <- dataf%>%group_by(year=format(date,"%Y"))%>%
                    dplyr::summarise(date=date[which.max(!!mvar)], wd=max(!!mvar))

I also tried with mvar <- enquo(mvar), but it doesn't work.我也尝试使用 mvar <- enquo(mvar),但它不起作用。 What am I missing?我错过了什么? Both worked when using WD directly, instead.!mvar.两者都在直接使用 WD 时工作,而不是.!mvar。

Thanks in advance!提前致谢!

It looks like your using an older approach to programming with dplyr .看起来您使用的是旧方法来使用 dplyr 进行编程 Enquo() and !! Enquo()!! aren't used anymore.不再使用。

It's hard to be sure what you want to achieve without your data, but, if you pass the variable directly (as you do in dplyr pipes, you can embrace it {{ var }} in a function. If you're passing a string name for the variable, you need you use .data[[var]] :在没有数据的情况下很难确定你想要实现什么,但是,如果你直接传递变量(就像你在dplyr管道中所做的那样,你可以在 function 中包含它{{ var }} 。如果你传递一个字符串变量的名称,您需要使用.data[[var]]

library(tidyverse)

# pass variable directly
my_func_var <- function(df, var){
  df %>% slice_max({{ var }})
}

iris %>% my_func_var(Sepal.Length)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#> 1          7.9         3.8          6.4           2 virginica

# pass variable as string
my_func_str <- function(df, var){
  df %>% slice_max(.data[[var]])
}

my_var <- "Sepal.Length"
iris %>% my_func_str(my_var)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#> 1          7.9         3.8          6.4           2 virginica

Created on 2021-04-23 by the reprex package (v1.0.0)代表 package (v1.0.0) 于 2021 年 4 月 23 日创建

(I used slice_max() as it felt more natural, but which.max() seems to work too) (我使用slice_max()因为它感觉更自然,但which.max()似乎也有效)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM