dplyr - from group_by into own function

前端 未结 1 1550
离开以前
离开以前 2020-12-22 08:33

This is quite possibly a duplicate of either or both of these, if so apologies and I guess that would make it an outstanding burning issue.

https://stackoverflow.com

1条回答
  •  太阳男子
    2020-12-22 08:41

    Turning my and docendo's comments into an answer, this is what do() is for.

    mtcars %>% group_by(cyl, am) %>% do(blah(.))
    # same results as
    plyr::ddply(mtcars, plyr::.(cyl, am), function(x) blah(x))
    # same as plyr with no anonymous function in this case
    plyr::ddply(mtcars, plyr::.(cyl, am), blah)
    

    Because blah is taking in your full data frame (at least in terms of columns) and returning a data frame, you don't need the anonymous function call.

    A lot is similar between dplyr and ddply, if you want to add columns, you use mutate, if you want to collapse grouping variables with aggregate functions, you use summarise. do is the dplyr equivalent of doing something else to each piece of data, but it needs to return a data frame.

    0 讨论(0)
提交回复
热议问题