Assigning names to the list output of dplyr do operation

后端 未结 2 1803
借酒劲吻你
借酒劲吻你 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:17

    You can create a data.frame within your function:

     mods <- do(group_by(it,ind),function(x)
            data.frame(it=unique(as.character(x$ind)),val=min(x$var1)))
    

    Then :

    do.call(rbind,mods)
      it val
    1  a   1
    2  b   3
    3  c   5
    

    EDIT

     mods <- do(group_by(it,ind),
          function(x) setNames(list(min(x$var1)),unique(as.character(x$ind))))
    
    unlist(mods,rec=FALSE)
    $a
    [1] 1
    
    $b
    [1] 3
    
    $c
    [1] 5
    
    0 讨论(0)
  • 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.

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