【问题标题】:Dplyr & purrr with dynamic column names, select & copy by group具有动态列名的 Dplyr 和 purrr,按组选择和复制
【发布时间】:2018-06-05 09:08:50
【问题描述】:

我有以下代码,我需要从变量中获取列名,然后使用该操作中的指定列有选择地对行执行操作。这是我的简单示例,创建列res 以匹配列target:

library(tidyverse)

tst <- tibble(grp = c("a","a","b","b","c","c"), a = rep(2,6), b = rep(4,6), 
              c = rep(8,6), target = c(2,2,4,4,8,8), res = rep(0,6))

# create list of columns to iterate over
lst <-  unique(tst$grp)

# loop over each column, creating a dummy column with 
# the copied value in the matching rows, zeroes elsewhere
for(g in lst) {

  tst <- tst %>% 
    mutate(!!paste("res", g, sep="_") := ifelse(grp == g, !!rlang::sym(g),0)) %>% 
    select(!!paste("res", g, sep="_")) %>% 
    cbind(tst)
}

# combine the dummy columns by rowSum
res <- tst %>% select(starts_with("res_")) %>% mutate(res = rowSums(.)) %>% 
select(res)

# tidy up the output, result matches the target
tst <- tst %>% select(grp, a, b, c, target) %>% cbind(res)

tst

  grp a b c target res
1   a 2 4 8      2   2
2   a 2 4 8      2   2
3   b 2 4 8      4   4
4   b 2 4 8      4   4
5   c 2 4 8      8   8
6   c 2 4 8      8   8

我采用了一种迭代方法,循环遍历 grp 列中的唯一变量,创建临时列然后 rowSum()ing 这些以获得最终结果。笨重,但最终到达那里。

我确信有一种更优雅的方法可以使用来自purrr 的map 家族之一。有人可以告诉我如何在没有循环的情况下使用purrr 做到这一点吗?我真的很努力让动态列名使用这种方法工作。提前致谢。

【问题讨论】:

    标签: r dplyr purrr


    【解决方案1】:

    不需要你写循环的东西

    library(tidyverse)
    
    tst <- tibble(grp = c("a","a","b","b","c","c"), a = rep(2,6), b = rep(4,6), 
                  c = rep(8,6), target = c(2,2,4,4,8,8), res = rep(0,6))
    
    tst %>% 
      mutate(res = 
               case_when(
                 grp == "a" ~ a,
                 grp == "b" ~ b,
                 grp == "c" ~ c
               ))
    
    # A tibble: 6 x 6
      grp       a     b     c target   res
      <chr> <dbl> <dbl> <dbl>  <dbl> <dbl>
    1 a         2     4     8      2     2
    2 a         2     4     8      2     2
    3 b         2     4     8      4     4
    4 b         2     4     8      4     4
    5 c         2     4     8      8     8
    6 c         2     4     8      8     8
    

    注意:如果需要,您可以使用自己的公式代替 ~ a。
    如需更多帮助,请参阅?case_when

    【讨论】:

      【解决方案2】:

      您可以使用imap,它会迭代列值及其名称。列值是grp 的值,名称只是序列1,...,6。

      此外,您必须提供数据框本身作为附加参数(df= 到 imap,它会将其转发给它的函数参数。总共:

      tst %>% 
        mutate(res = purrr::imap_dbl(grp, df = ., 
          .f = function(g, i, df) df[i,g][[1]] # [[1]] turns the result from tibble into a double
        )) 
      

      编辑:我用一个更大的表来计时这个解决方案:

      tst <- tst[sample(nrow(tst), 50000, TRUE),]
      

      大约需要 50 秒。

      【讨论】:

      • 谢谢,这就是我想要的
      • @ScottSimpson 如果你有一个大的(>10000 行)表,你可能想看看pure R solution,它快了 5000 倍。
      【解决方案3】:

      这是一个基本的 R 解决方案,也不再是:

      # Save all source columns in a matrix. This enables indexing by another matrix
      x <- as.matrix(tst[, unique(tst$grp)])
      # Matrix of (row, column) pairs to extract from x
      i <- cbind(seq_len(nrow(tst)), match(tst$grp, colnames(x)))
      tst$res <- x[i]
      

      编辑:较大表的经过时间:

      tst <- tst[sample(nrow(tst), 50000, TRUE), ]
      

      0.008s -- 0.015s

      【讨论】:

        【解决方案4】:

        也许:

        tst %>% 
          mutate(res = sapply(seq(nrow(tst)), function(x) tst[x,as.character(tst$grp[x])]))
        
        
        # A tibble: 6 x 6
            grp     a     b     c target   res
          <chr> <dbl> <dbl> <dbl>  <dbl> <dbl>
        1     a     2     4     8      2     2
        2     a     2     4     8      2     2
        3     b     2     4     8      4     4
        4     b     2     4     8      4     4
        5     c     2     4     8      8     8
        6     c     2     4     8      8     8
        

        【讨论】:

        • 谢谢,很有帮助
        猜你喜欢
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 2023-01-27
        • 1970-01-01
        • 2018-11-05
        • 2018-07-30
        • 1970-01-01
        • 2019-07-21
        相关资源
        最近更新 更多