17

The following works fine:

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
AndrewMacDonald
  • 2,870
  • 1
  • 18
  • 31

2 Answers2

20

You don't need an anonymous function:

library(dplyr)
iris %>%
  group_by(Species) %>%
  do({
    mod <- lm(Sepal.Length ~ Sepal.Width, data = .)
    pred <- predict(mod, newdata = .["Sepal.Width"])
    data.frame(., pred)
  })
hadley
  • 102,019
  • 32
  • 183
  • 245
  • As fun as the other answer was, this answer is much cleaner! I keep forgetting that `.` can be a pronoun for the entire dataset. – AndrewMacDonald Jun 24 '14 at 14:02
13

You can't get rid of the ..

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

That will work. The . is necessary. The . is love. Keep the ..

stanekam
  • 3,906
  • 2
  • 22
  • 34
  • I love this answer so much! I had tried that, but i'd forgotten to wrap the function in () first :$ – AndrewMacDonald Jun 24 '14 at 01:38
  • 4
    could you explain what's going on here? Why is the function in ()?And why is the dot needed? And why is the dot in ()? – Rik Smith-Unna Nov 14 '14 at 23:45
  • It is absolutely not clear what is going on here from a syntax point of view... – PejoPhylo Feb 03 '20 at 12:11
  • The function is in parentheses because it is being created anonymously and then called with the alias of `.` as the argument. Wrapping the anonymous function definition in parentheses is necessary because then it gets returned as an object to be called. Remove the parentheses and you have a syntax error. – stanekam Oct 13 '20 at 07:06