dplyr将具有更改参数的单个函数应用于同一列 [英] dplyr apply a single function with changing argument to the same column

查看:48
本文介绍了dplyr将具有更改参数的单个函数应用于同一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只有一列的简单df,我想使用一个函数(在这种情况下为 sum_x )创建一个新的多列,而只更改一个参数.有没有一种方法比我在下面的 dplyr 中显示的方法更有效?理想情况下,我可以合并 sum_vec 并在一行中完成,以创建100个新列.这似乎是一个非常简单的问题,但我不知道如何使用 dplyr 有效解决此问题.

I have a simple df with one column, and I want to create multiple new columns using a single function (sum_x in this case) with only an argument changing. Is there a way to do this more efficiently than the way I have shown below in dplyr? Ideally I could incorporate sum_vec and do this in a single line to create 100 new columns. This seems to be a very simple problem, but I don't know how to solve this efficiently using dplyr.

df <- data.frame(x = 1:20)
sum_x <- function(x, y){
 x + y
}

sum_vec <- 1:100
df %>% mutate(x_1 = sum_x(x, 1)) %>% mutate(x_2 = sum_x(x, 2)) %>% mutate(x_3 = sum_x(x, 3))

推荐答案

以这种方式尝试

library(tidyverse)
bind_cols(df, map_dfc(1:3, ~ df %>% transmute(!!paste0("x_", .x) := x + .x)))

    x x_1 x_2 x_3
1   1   2   3   4
2   2   3   4   5
3   3   4   5   6
4   4   5   6   7
5   5   6   7   8
6   6   7   8   9
7   7   8   9  10
8   8   9  10  11
9   9  10  11  12
10 10  11  12  13
11 11  12  13  14
12 12  13  14  15
13 13  14  15  16
14 14  15  16  17
15 15  16  17  18
16 16  17  18  19
17 17  18  19  20
18 18  19  20  21
19 19  20  21  22
20 20  21  22  23

这篇关于dplyr将具有更改参数的单个函数应用于同一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆