Add multiple output variables using purrr and a predefined function

前端 未结 3 802
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 06:33

Take this simple dataset and function (representative of more complex problems):

x <- data.frame(a = 1:3, b = 2:4)
mult <- function(a,b,n) (a + b) * n
         


        
3条回答
  •  醉梦人生
    2021-01-05 06:44

    To mimic the input format for Map, we could call pmap from purrr in this way:

    x[paste0("new",seq_along(ns))] <- pmap(list(x['a'], x['b'], ns), mult)
    

    To fit this in a pipe:

    x %>%
        {list(.['a'], .['b'], ns)} %>%
        pmap(mult) %>%
        setNames(paste0('new', seq_along(ns))) %>%
        cbind(x)
    
    #   new1 new2 a b
    # 1    3    6 1 2
    # 2    5   10 2 3
    # 3    7   14 3 4
    

    Apparently, this looks ugly compared to the concise base R code. But I could not think of a better way.

提交回复
热议问题