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