将 mutate 与存储的列和过程列表一起使用 [英] Using mutate with a stored list of columns and procedures

查看:41
本文介绍了将 mutate 与存储的列和过程列表一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历存储的列和过程列表,以基于此列表创建 n 个新列.在下面的例子中,我们从 3 列开始,a, b, c 和两个简单​​的函数 func1, func1.

I would like to iterate through a stored list of columns and procedures to create n new columns based on this list. In the example below, we start with 3 columns, a, b, c and two simple functions func1, func1.

数据框 col_mod 包含两组应应用于数据框的修改.这些修改中的每一个都应该是对数据框的补充,而不是对指定列的替换.

The data frame col_mod contains two sets of modifications that should be applied to the data frame. Each of these modifications should be an addition to the data frame, rather than replacements of the specified columns.

col_mod 行 1 中,我们看到列 a 应该使用 func1 进行修改,而在第 2 行中,我们看到列 c 应该使用 func2 修改.这些列的新名称应分别为 a_newc_new.

In col_mod row 1, we see that column a should be modified using func1, and in row 2, we see that column c should be modified using func2. The new names of these columns should be a_new and c_new, respectively.

在下面的 reprex 的底部,我得到了我想要的结果,但我想这样做而不是单独对每个修改进行硬编码.有什么方法可以使用 purrr:map 或类似的东西吗?

At the bottom of the reprex below, I obtain my desired result, but I would like to do so without hard coding each modification individually . Is there any way to use maybe something from purrr:map or anything similiar?

library(tidyverse)

## fake data
dat <- data.frame(a = 1:5,
                  b = 6:10,
                  c = 11:15)

## functions
func1 <- function(x) {x + 2}
func2 <- function(x) {x - 4}

## modification list
col_mod <- data.frame("col" = c("a", "c"),                      
                  "func" = c("func1", "func2"), 
                  stringsAsFactors = FALSE)

## desired end result
dat %>% 
  mutate("a_new" = func1(a),
         "c_new" = func2(c))

如果将修改存储在列表中更容易,如下所示,使用它的解决方案也很好,因为我能够将修改存储在数据中框架或列表.

edit: if it is easier to store the modifications in a list, as shown below, a solution using that would be fine as well, as I am able to store the modifications in either a data frame or list.

col_mod <- list("set1" = list("a", "func1"),
                "set2" = list("c", "func2"))

推荐答案

我们可以借助Map来实现,使用match.fun来应用该功能

We can do this with the help of Map, use match.fun to apply the function

dat[paste0(col_mod$col, '_new')] <- Map(function(x, y) match.fun(y)(x), 
                                      dat[col_mod$col], col_mod$func)
dat

#  a  b  c a_new c_new
#1 1  6 11     3     7
#2 2  7 12     4     8
#3 3  8 13     5     9
#4 4  9 14     6    10
#5 5 10 15     7    11

使用 col_mod 作为数据帧.

col_mod <- data.frame("col" = c("a", "c"),"func" = c("func1", "func2"))

这篇关于将 mutate 与存储的列和过程列表一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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