首页 > 解决方案 > 在 dplyr 中创建一个通过变量/字符串操作对列进行操作的函数

问题描述

我正在处理一个数据集,该数据集包含许多名称相似的列(例如thing_1, thing_2, blargh_1, blargh_2, fizz_1, fizz_2),并且我一直在尝试编写一个函数,该函数接受一个字符串(例如fizz)并对所有超字符串执行一些操作列(例如fizz_1 + fizz_2)。

到目前为止,我已经将我的代码结构化为如下所示:

newData <- data %>%
    mutate(fizz = f("fizz"))

f <- function(name) {
name_1 + name_2
}

在哪里f写的显然行不通。我玩弄过assign,但不是很成功。我也对解决问题的其他方法持开放态度(可能是一个接收数据集和字符串的函数)。谢谢!

标签: rdplyr

解决方案


如果我们正在创建一个函数,那么使用select_helperswhich 可以接受starts_withorends_withmatch作为参数

library(dplyr)
library(purrr)
f1 <- function(data, name){
          data %>%
              mutate(!! name := select(., starts_with(name)) %>% reduce(`+`))
    }

f1(df1, "fizz")
f1(df1, "blargh")
f1(df1, "thing")
#   thing_1 thing_2 thing_3 fizz_1 fizz_2 blargh_1 blargh_2 thing
#1       1       6      11      2      3        4        5    18
#2       2       7      12      3      4        5        6    21
#3       3       8      13      4      5        6        7    24
#4       4       9      14      5      6        7        8    27
#5       5      10      15      6      7        8        9    30

或指定select(., matches(str_c("^", name, "_\\d+$")))

数据

df1 <- data.frame(thing_1 = 1:5, thing_2 = 6:10, thing_3 = 11:15, 
    fizz_1 = 2:6, fizz_2 = 3:7, blargh_1 = 4:8, blargh_2 = 5:9)

          

推荐阅读