首页 > 解决方案 > 'mutate' 在 R 中的 tidyverse 中添加两列,其中包含一个 fn 调用

问题描述

这是一个 R 版本 3.4.4 问题

一个投票函数voteOnBase,接受 2 个参数并返回一个 2 元素列表: theWINNER和 the VOTE.COUNT。我想用它将这两列添加到notVotedYettibble。以下代码运行正确。

 library(tidyverse)

 withVotes <- notVotedYet %>%
    group_by(BASE) %>%
    mutate(WINNER     = voteOnBase(BASE, CODES)[[1]],
           VOTE.COUNT = voteOnBase(BASE, CODES)[[2]])

但是,它会voteOnBase在相同的输入上调用两次。如何消除额外的函数调用但仍添加相同的两列?

标签: rdplyrprocessing-efficiencymagrittr

解决方案


没有一些示例数据和输出就不容易回答,但我建议写voteOnBase()返回一个小标题,而不是一个列表。然后,您可以将结果存储在列表列中并使用创建列unnest()

举例说明:这里有一个函数,square_it()它和你的一样,接受 2 个参数并返回 2 个元素 - 但作为 tibble 中的列。

square_it <- function(x, y) {
  tibble(x = x^2, y = y^2)
}

我们可以使用iris数据集来传递参数。我们pmap()用来指定变量和函数。列表列名为sq

iris %>% 
  as_tibble() %>% 
  mutate(sq = pmap(list(Sepal.Length, Sepal.Width), square_it))

# A tibble: 150 x 6
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species sq              
          <dbl>       <dbl>        <dbl>       <dbl> <fct>   <list>          
 1          5.1         3.5          1.4         0.2 setosa  <tibble [1 x 2]>
 2          4.9         3            1.4         0.2 setosa  <tibble [1 x 2]>
 3          4.7         3.2          1.3         0.2 setosa  <tibble [1 x 2]>
 4          4.6         3.1          1.5         0.2 setosa  <tibble [1 x 2]>
 5          5           3.6          1.4         0.2 setosa  <tibble [1 x 2]>
 6          5.4         3.9          1.7         0.4 setosa  <tibble [1 x 2]>
 7          4.6         3.4          1.4         0.3 setosa  <tibble [1 x 2]>
 8          5           3.4          1.5         0.2 setosa  <tibble [1 x 2]>
 9          4.4         2.9          1.4         0.2 setosa  <tibble [1 x 2]>
10          4.9         3.1          1.5         0.1 setosa  <tibble [1 x 2]>
# ... with 140 more rows

只需添加%>% unnest(sq)到该代码,以生成列xy

iris %>% 
  as_tibble() %>% 
  mutate(sq = pmap(list(Sepal.Length, Sepal.Width), square_it)) %>%
  unnest(sq)

# A tibble: 150 x 7
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species     x     y
          <dbl>       <dbl>        <dbl>       <dbl> <fct>   <dbl> <dbl>
 1          5.1         3.5          1.4         0.2 setosa   26.0 12.2 
 2          4.9         3            1.4         0.2 setosa   24.0  9   
 3          4.7         3.2          1.3         0.2 setosa   22.1 10.2 
 4          4.6         3.1          1.5         0.2 setosa   21.2  9.61
 5          5           3.6          1.4         0.2 setosa   25   13.0 
 6          5.4         3.9          1.7         0.4 setosa   29.2 15.2 
 7          4.6         3.4          1.4         0.3 setosa   21.2 11.6 
 8          5           3.4          1.5         0.2 setosa   25   11.6 
 9          4.4         2.9          1.4         0.2 setosa   19.4  8.41
10          4.9         3.1          1.5         0.1 setosa   24.0  9.61
# ... with 140 more rows

推荐阅读