2

Consider the following table:

df <- as.tbl(data.frame(grp=c("a","b","c","d","e"), a=1:5, b=6:10))

Let's say I want to add a column to the table that is the product of columns a and b.

I could just do df$product <- df$a * df$b. If I want to use do() the following works:

df %>% group_by(grp) %>% do({
  d <- .
  d$product <- d$a * d$b
  d #expression returns the data frame, d
})

#result is as expected
     grp     a     b product
  <fctr> <int> <int>   <int>
1      a     1     6       6
2      b     2     7      14
3      c     3     8      24
4      d     4     9      36
5      e     5    10      50

But it does not work as expected when I assign to .:

df %>% group_by(grp) %>% do({
  .$product <- .$a * .$b
  .
})

#The output only includes data from row 1 (grp==a) of the input
     grp     a     b product
  <fctr> <int> <int>   <int>
1      a     1     6       6
2      a     1     6       6
3      a     1     6       6
4      a     1     6       6
5      a     1     6       6
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
Al R.
  • 2,430
  • 4
  • 28
  • 40
  • Please expand on how your second effort "does not work". `dplyr` is still very much version < 1 and so we need more information on how it "does not work" for you. Errors? Wrong numbers? Computer explodes? – Spacedman Jul 14 '17 at 15:00
  • The simplest answer is “you cannot assign to `.`” but that’s of course quite unsatisfactory. – Konrad Rudolph Jul 14 '17 at 15:01
  • 1
    @KonradRudolph both examples work fine if you don't have the group_by, so it seems that under some circumstances you can assign to ".", or at least you can get away with it. But I'd agree, "." is special and don't play with it. Ever. – Spacedman Jul 14 '17 at 15:03
  • @Spacedman Yeah, assignment to `.` is simply undefined behaviour. Literally, since it’s quite undocumented. – Konrad Rudolph Jul 14 '17 at 15:04
  • I'm using dplyr version 0.7.1, R version 3.4.0, Ubuntu 17.04 – Al R. Jul 14 '17 at 15:09
  • 1
    I think this should be reported as a bug. – Hong Ooi Jul 14 '17 at 15:26
  • 1
    @ChiPak Fyi, SO chat rooms are probably a better venue for comments that don't fit in the comment box (like your deleted answer below). – Frank Jul 14 '17 at 15:28
  • 1
    @Frank Thanks, I'll look into it. Definitely a better idea than posting a non-answer Answer – CPak Jul 14 '17 at 15:30
  • 4
    https://github.com/tidyverse/dplyr/issues/2970 – Hong Ooi Jul 14 '17 at 15:36

0 Answers0