r - 如何总结自定义 dplyr 函数中的变量列表?
问题描述
初始点:
我有一个数据集(tibble),其中包含许多同一类(dbl)的变量。它们属于不同的设置。缺少变量(tibble 中的列)。这是属于一个设置的所有变量的 rowSum。
目标:
我的目标是为每个设置生成具有相同数据结构的子数据集,包括“rowSum”-Variable(我称之为“s1”)。
问题:
在每个设置中都有不同数量的变量(当然它们的名称也不同)。因为它应该是具有不同变量的相同结构,所以它是函数的典型情况。
问题:
如何使用 dplyr 解决问题?
我写了一个函数
(1)为有趣的设置(正在工作)子集原始数据集和
(2) 尝试对设置的变量进行rowSums(不起作用;为什么?)。
因为它是针对特殊设计的数据集的函数,所以该函数包含两个预定义变量:
day - 调查期间的任何一天
N - 这是在这个特殊的日子调查的案件数
感谢您的任何帮助。
mkr.sumsetting <- function(...,dataset){
subvars <- rlang::enquos(...)
#print(subvars)
# Summarize the variables belonging to the interessting setting
dfplot <- dataset %>%
dplyr::select(day,N,!!! subvars) %>%
dplyr::mutate(s1 = rowSums(!!! subvars,na.rm = TRUE))
return(dfplot)
}
解决方案
我们可以将其更改为字符串和as_name
子集数据集[[
rowSums
library(rlang)
library(purrr)
library(dplyr)
mkr.sumsetting <- function(...,dataset){
subvars <- rlang::enquos(...)
v1 <- map_chr(subvars, as_name)
#print(subvars)
# Summarize the variables belonging to the interessting setting
dfplot <- dataset %>%
dplyr::select(day, N, !!! subvars) %>%
dplyr::mutate(s1 = rowSums( .[v1],na.rm = TRUE))
return(dfplot)
}
out <- mkr.sumsetting(col1, col2, dataset = df1)
head(out, 3)
# day N col1 col2 s1
#1 1 20 -0.5458808 0.4703824 -0.07549832
#2 2 20 0.5365853 0.3756872 0.91227249
#3 3 20 0.4196231 0.2725374 0.69216051
或者另一种选择是select
然后quosure
做rowSums
mkr.sumsetting <- function(...,dataset){
subvars <- rlang::enquos(...)
#print(subvars)
# Summarize the variables belonging to the interessting setting
dfplot <- dataset %>%
dplyr::select(day, N, !!! subvars) %>%
dplyr::mutate(s1 = dplyr::select(., !!! subvars) %>%
rowSums(na.rm = TRUE))
return(dfplot)
}
mkr.sumsetting(col1, col2, dataset = df1)
数据
set.seed(24)
df1 <- data.frame(day = 1:20, N = 20, col1 = rnorm(20),
col2 = runif(20))
推荐阅读
- android - 为什么我将 Target SDK 从 28 降低到 27 时出现“Android 资源链接失败”错误?
- if-statement - Puppet reboot when notifed AND parameter set to true
- handlebars.js - 从 webdav 注入 HTML 文件
- kotlin - 如何在不使用匕首的情况下创建通用视图模型工厂?
- python - 如何从另一个目录运行模块?
- android - 如何在 roboelctric 测试中初始化 firebase
- java - 如何为带有数字括号的“名称(2)”单词制作正则表达式
- c# - Unity 错误 CS0246(找不到命名空间)
- assemblyscript - AssemblyScript 中的 TypedArray 与 Array
- mocking - 在 Jest 中模拟具有进行 Axios 调用的函数的对象