[R] pass by reference
Kenn Konstabel
lebatsnok at gmail.com
Tue Aug 14 12:28:52 CEST 2012
You can use macros for this effect. Or environments:
daf <- data.frame(a=1:10, b=rnorm(10))
env <- as.environment(daf)
fun <- function(x) x$c <- x$a+x$b
fun(daf)
fun(env)
daf$c
env$c
You can see that the same function (fun) changes one object but leaves
another one unchanged. But before using it for something important,
think of the side effects and efficiency. Passing by value does not
create as many unnecessary copies as one might think.
On Tue, Aug 14, 2012 at 4:08 AM, Sachinthaka Abeywardana
<sachin.abeywardana at gmail.com> wrote:
> Hi all,
>
> I want to do the following:
>
> data<-data.frame(col1=c(1,2,3,4,5))
>
> getcol2<-function(data){
> data$col2[data$col1<=2]="L"
> }
>
> getcol2(data)
>
> Unfortunately in the above col2 does not appear in the final data. So how
> would you pass this by reference such that you would get it back?
>
> Thanks,
> Sachin
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list