【问题标题】:How to sum up a list of variables in a customized dplyr function?如何总结自定义 dplyr 函数中的变量列表?
【发布时间】:2019-05-10 05:38:04
【问题描述】:

起点:

我有一个数据集(tibble),其中包含许多同一类(dbl)的变量。它们属于不同的设置。缺少变量(tibble 中的列)。这是属于一个设置的所有变量的 rowSum。

目标:

我的目标是为每个设置生成具有相同数据结构的子数据集,包括“rowSum”-Variable(我称之为“s1”)。

问题:

在每个设置中都有不同数量的变量(当然它们的名称也不同)。 因为它应该是具有不同变量的相同结构,所以这是一个函数的典型情况。

问题:

如何使用 dplyr 解决问题?

我写了一个函数来

(1) 为有趣的设置(正在工作)和

子集原始数据集

(2) 尝试对设置的变量进行行求和(不起作用;为什么?)。

因为它是针对特殊设计的数据集的函数,所以该函数包含两个预定义变量:

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)
   }

【问题讨论】:

标签: r function dplyr


【解决方案1】:

我们可以使用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

或者另一种选择是selectquosure,然后执行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))

【讨论】:

  • 谢谢!有用。我想我现在已经理解了编程 dplyr 函数的想法。
猜你喜欢
  • 2017-12-18
  • 2017-12-25
  • 1970-01-01
  • 2017-09-08
  • 2017-11-27
  • 1970-01-01
  • 2020-07-04
  • 2021-09-06
  • 1970-01-01
相关资源
最近更新 更多