I think the best advice is: Don't do that!
transform()
, with()
, subset()
are really sugar for use at the top level, to make things somewhat easier to write data manipulation code. If you are writing functions you should use the general replacement functions [<-
and [[<-
depending on what you are doing.
If you don't believe me, see the Warning in ?transform
Warning: This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting arithmetic functions, and in particular the non-standard evaluation of argument ‘transform’ can have unanticipated consequences.
What I mean by using [<-
or [
or other functions is to write f
like this
f <- function(obj, x) {
cd <- coredata(obj)
cd <- cbind(cd, c = x * cd[, "a"])
zoo(cd, index(obj), attr(obj, "frequency"))
}
f(z, 2)
Which gives the desired result
> transform(z, c = x*a)
a b c
2001 1 6 2
2002 2 7 4
2003 3 8 6
2004 4 9 8
2005 5 10 10
> f(z, 2)
a b c
2001 1 6 2
2002 2 7 4
2003 3 8 6
2004 4 9 8
2005 5 10 10
f
is complicated because coredata(obj)
is a matrix. It might be neater to
f2 <- function(obj, x) {
cd <- as.data.frame(coredata(obj))
cd[, "c"] <- x * cd[, "a"] ## or cd$c <- x * cd$a
zoo(cd, index(obj), attr(obj, "frequency"))
}
f2(z, 2)
> f2(z, 2)
a b c
2001 1 6 2
2002 2 7 4
2003 3 8 6
2004 4 9 8
2005 5 10 10
You really need to understand environments and evaluation frames to use transform()
- well you can't you'd need to learn to use eval()
, which is what transform()
calls internally, and specify the correct values for envir
(the environment in which to evaluate), and enclos
the enclosure. See ?eval
.