pass by reference
You can write the replacement-function like [the untested[
`col2<-` <- function(x, ..., value) {
x$col2[x$col1 < 2] <- value
x
}
so you can do modifications with the syntax
col2(data) <- "L"
If you also write the matching extractor
col2 <- function(x) x$col2[x$col1 < 2]
then you can nest replacements with
col2(data)[2] <- "L"
I like this syntax because it makes clear what is being modified
(things to the left of the assignment operator). It may
or may not save memory or time, but as R develops
replacement functions may get more efficient.
By the way, the syntax
f <- function(data) {
data <<- modify(data)
}
is terrible because calling f(argument) creates a dataset called 'data'
(not 'argument') in some ancestral environment of the function (which
environment depends on where a previous dataset called 'data'
may have been defined).
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
Of rest
Sent: Tuesday, August 14, 2012 1:00 AM
To: 'Sachinthaka Abeywardana'; r-help at r-project.org
Subject: Re: [R] pass by reference
Hi Sachinthaka,
You can do it in the following way:
getcol2<-function(data){
data$col2[data$col1<=2]="L"
data<<-data
}
<<- writes the result to the underlying environment. This is however
generally seen as very bad programming (side effects).
Greet'
Frans-----Oorspronkelijk bericht-----
Van: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
Namens Sachinthaka Abeywardana
Verzonden: dinsdag 14 augustus 2012 3:08
Aan: r-help at r-project.org
Onderwerp: [R] pass by reference
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. ______________________________________________ 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.