r - 在 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
,但不是很成功。我也对解决问题的其他方法持开放态度(可能是一个接收数据集和字符串的函数)。谢谢!
解决方案
如果我们正在创建一个函数,那么使用select_helpers
which 可以接受starts_with
orends_with
或match
作为参数
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)
推荐阅读
- c - 我正在编写一个程序,它将删除数组中重复的数字。使用指针通过函数传递数组
- node.js - 在猫鼬中等待与执行
- c - 是否可以使用变量声明数组?
- python - 我可以使用已经创建的对象来调试代码吗 - Pycharm
- typescript - 使用 Firebase 订购
- react-native - 使用 React Native 点击并按住透明上下文菜单?
- r - 如何在 R 中对 textstem 的词典进行大量补充?
- javascript - 无法让 innerHTML 正常工作
- android - 将片段添加到 Backstack 失败
- python - 了解 CNN 中的 batch_size