Assigning names to the list output of dplyr do operation

后端 未结 2 1804
借酒劲吻你
借酒劲吻你 2021-01-03 06:38

The do function in the package dplyr usually produces the list. Is there are way to assign names to that list depending on the input to d

2条回答
  •  伪装坚强ぢ
    2021-01-03 07:23

    Try this marked up version of do.grouped_df:

    do2 <- function (.data, .f, ...) {
        if (is.null(attr(.data, "indices"))) {
            .data <- dplyr:::grouped_df_impl(.data, attr(.data, "vars"), 
                attr(.data, "drop"))
        }
        index <- attr(.data, "indices")
        out <- vector("list", length(index))
        for (i in seq_along(index)) {
            subs <- .data[index[[i]] + 1L, , drop = FALSE]
            out[[i]] <- .f(subs, ...)
        }
        nms <- as.character(attr(.data, "labels")[[1]])
        setNames(out, nms)
    }
    
    library(gusbfn)
    
    it %.% group_by(ind) %.% do2(function(x) min(x$var1))
    

    which gives:

    $a
    [1] 1
    
    $b
    [1] 3
    
    $c
    [1] 5
    

    It could also be combined with fn$ from the gsubfn package like this to shorten it slightly:

    library(dplyr)
    library(gsubfn)
    
    it %.% group_by(ind) %.% fn$do2(~ min(x$var1))
    

    giving the same answer.

提交回复
热议问题