首页 文章

dplyr使用数据帧的功能进行汇总

提问于
浏览
7

我在使用 dplyr 包执行例程时遇到了一些麻烦 . 简而言之,我有一个函数,它将数据帧作为输入,并返回一个(数字)值;我'd like to be able to apply this function to several subsets of a dataframe. It feels like I should be able to use group_by() to specify the subsets of the dataframe, then pipe along to the summarize() function, but I'我不知道如何将(子集化的)数据帧传递给我想要应用的函数 .

作为简化示例,让's say I' m使用 iris 数据集,并且我想要应用于数据的几个子集:

data(iris)
lm.func = function(.data){
  lm.fit = lm(Petal.Width ~ Petal.Length, data = .data)
  out = summary(lm.fit)$coefficients[2,1]
  return(out)
}

现在,我希望能够将此函数应用于 iris 的子集,基于其他变量,如 Species . 我能够手动过滤数据,然后管道到我的功能,例如:

iris %>% filter(Species == "setosa") %>% lm.func(.)

但我希望能够根据Species将 lm.func 应用于数据的每个子集 . 我的第一个想法是尝试类似以下内容:

iris %>% group_by(Species) %>% summarize(coef.val = lm.func(.))

即使我知道这不起作用,我的想法是尝试将每个虹膜子集传递给lm.func函数 .

为了澄清,我想最终得到一个包含两列的数据框 - 第一个是每个级别的分组变量,第二个是输出 lm.func ,当数据被限制为分组变量指定的子集时 .

是否可以以这种方式使用summarize()?

2 回答

  • 3

    你可以试试 do

    iris %>% 
          group_by(Species) %>%
          do(data.frame(coef.val=lm.func(.)))
     #     Species  coef.val
     #1     setosa 0.2012451
     #2 versicolor 0.3310536
     #3  virginica 0.1602970
    
  • 11

    没有创建功能,有一种简单的方法 .

    library(broom)
    models <-iris %>% 
      group_by(Species) %>%
      do(
        mod = lm(Petal.Width ~ Petal.Length, data =.)
      )
    
      models %>% do(tidy(.$mod))
    
              term    estimate  std.error  statistic      p.value
    1  (Intercept) -0.04822033 0.12164115 -0.3964146 6.935561e-01
    2 Petal.Length  0.20124509 0.08263253  2.4354220 1.863892e-02
    3  (Intercept) -0.08428835 0.16070140 -0.5245029 6.023428e-01
    4 Petal.Length  0.33105360 0.03750041  8.8279995 1.271916e-11
    5  (Intercept)  1.13603130 0.37936622  2.9945505 4.336312e-03
    6 Petal.Length  0.16029696 0.06800119  2.3572668 2.253577e-02
    

相关问题