In dplyr::do()
, is there a way to access variables in the context of .data
as with other dplyr functions? For instance, say I have a data frame:
> dd <- data.frame(a=1:5)
mutate()
, as well as other functions, works so that expressions are evaluated in the context of the data frame:
> mutate(dd,a2=a*2)
a a2
1 1 2
2 2 4
3 3 6
4 4 8
5 5 10
But not do
:
> do(dd,data.frame(a2=a[1:2]*2))
Error in eval(expr, envir, enclos) : object 'a' not found
I can accomplish my objective using with()
and the dot pronoun:
> do(dd,with(.,data.frame(a2=a[1:2]*2)))
a2
1 2
2 4
I am also not sure why this doesn't work:
> do(dd,function(X) data.frame(a2=X$a[1:2]*2))
Error: Result must be a data frame
Questions:
- Is there logic to why this behavior (scope) is different from
mutate
,select
, etc. - Is there an elegant solution or I have
to keep using
with()
if I don't want to keep using.$variablename
in the expression? - Why doesn't the anonymous function work? Seems like it works here but not sure why my case is different.