[R] Getting at what a named object represents in a function...

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Oct 20 16:53:24 CEST 2007


Because of lazy evaluation, your function can find the expression for 
'param' by deparse(substitute(param)), provided that is called before 
'param' is actually used.  However, although that would allow you to 
change 'list' in the calling environment, that is regarded as really bad 
programming practice.

The normal way to do this would be to have

mylist$B <- foo(mylist$B)

but if you want you can write a replacement function to do

foo(mylist$B) <- new_value

by something like

`foo<-` <- function(x, value) {x[1:3] <- value; x}


On Sat, 20 Oct 2007, Martin Waller wrote:

> Hi,
>
> I'm pretty new to R.
>
> I have an object (say a list) and I I have a function that I call on
> various columns in that list (excuse terminology if it's wrong/ambiguous).
>
> Imagine its like this (actual values are unimportant) and called mylist:
>
> >mylist
> A    B
> 1    5
> 2    5
> 3    6  4    8
> 5    0
>
> I have a function:
>
> foo = function(param){
> #modify list A or B values depending on whether A or B's passsd in (via
> 'param')
>   param[someindex]=another_value #doesn't change value in lits$A or
> list$B (whichever's been passed in as 'param')
> #I want something like:
> #if 'param' is list$A then list$A[someindex]=another_value
> #else if 'param' is list$B then list$B[some_index] = another_value
> }
>
> I then call this function on mylist$A (i.e. foo(mylist$A) and then on
> mylist$B (i.e. foo(mylist$B))
>
> so 'param' in function foo is either mylist$A or mylist$B - can I tell
> which it is so that when param[someindex] is changed, it's actually
> mylist$A or mylist$B that's changed?
>
> If I modify param values in foo(), they're not modified in list...so is
> there a way to tell whether param represents list$A or list$B and hence
> allow to me to modify those actual values rather than 'param'?
>
> Thanks for help,
>
> Martin
>
> ______________________________________________
> 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.
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list