dplyr::do() 需要命名函数? [英] dplyr::do() requires named function?

查看:18
本文介绍了dplyr::do() 需要命名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下工作正常:

library(dplyr) 
m <- function(df) {
  mod <- lm(Sepal.Length ~ Sepal.Width, data = df)
  pred <- predict(mod,newdata = df["Sepal.Width"])
  data.frame(df,pred)
}
iris %>%
  group_by(Species) %>%
  do(m(.))

我认为如果我使用匿名函数这会起作用,但它不会:

I thought that this would work if I used an anonymous function, but it does not:

iris %>%
  group_by(Species) %>%
  do(function(df) {
    mod <- lm(Sepal.Length ~ Sepal.Width, data = df)
    pred <- predict(mod,newdata = df["Sepal.Width"])
    data.frame(df,pred)
  })
Error: Results are not data frames at positions: 1, 2, 3

推荐答案

你不需要匿名函数:

library(dplyr)
iris %>%
  group_by(Species) %>%
  do({
    mod <- lm(Sepal.Length ~ Sepal.Width, data = .)
    pred <- predict(mod, newdata = .["Sepal.Width"])
    data.frame(., pred)
  })

这篇关于dplyr::do() 需要命名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆