dplyr::group_by_ with character string input of several variable names

前端 未结 2 1201
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 06:36

I\'m writing a function where the user is asked to define one or more grouping variables in the function call. The data is then grouped using dplyr and it works as expected

2条回答
  •  离开以前
    2020-11-28 07:11

    slice_rows() from the purrrlyr package (https://github.com/hadley/purrrlyr) groups a data.frame by taking a vector of column names (strings) or positions (integers):

    y <- c("cyl", "gear")
    mtcars_grp <- mtcars %>% purrrlyr::slice_rows(y)
    
    class(mtcars_grp)
    #> [1] "grouped_df" "tbl_df"     "tbl"        "data.frame"
    
    group_vars(mtcars_grp)
    #> [1] "cyl"  "gear"
    

    Particularly useful now that group_by_() has been depreciated.

提交回复
热议问题