[R] how to pass object "members" in functions
Paul Rigor
pryce at ucla.edu
Wed Dec 22 21:51:19 CET 2010
Thanks for the clarification!
I actually got the function working by passing just the individual
objects as separate arguments. But creating a wrapper list object
should suffice and I'll just have the function return the modified
list object to achieve what I want.
Cheers,
Paul
On Wed, Dec 22, 2010 at 4:11 AM, Barry Rowlingson
<b.rowlingson at lancaster.ac.uk> wrote:
> On Wed, Dec 22, 2010 at 11:20 AM, Paul Rigor <pryce at ucla.edu> wrote:
>> Hello,
>> This is an R-syntax question when attempting to manipulate/access objects
>> when passed to a function.
>>
>> I have a function attempting to just print values attached to an argument
>> object. For example,
>>
>> printThis <- function(obj, parm2, parm3) {
>> print(obj.stuff1)
>> print(obj.stuff2)
>> }
>>
>> where I've assigned stuff1 and stuff2 to the actual object passed as such
>>
>> actualObject.stuff1 <- c("list","of","something")
>> actualObject.stuff2 <- c("list","of","something other thing")
>> printThis(actualObject) # actual call to the function above
>>
>>
>> But I'm getting the following error when calling the printThis method on
>> actualObject.
>> "object 'obj.stuff1' not found"
>>
>> How do I access all objects attached to a variable. I think I'm
>> misunderstanding this "." (dot) where it's most likely just an acceptable
>> way of naming variables in R.
>>
>> So what's the best way to create an object such that I can access what I've
>> assumed to be object properties?
>
> Yes, dot is just an allowed character in a variable name - it doesnt
> have the magical powers it has in Python or C or C++. You've created
> two objects called 'actualObject.stuff1' and 'actualObject.stuff2'
>
> The nearest equivalent to a C struct would probably be a list with named parts:
>
> foo = list(a=1, b=2)
> foo$a
> foo$b
>
> or you need to look at the object-oriented systems in R. Be warned
> that OO in R isn't much like OO in many other languages - there's at
> least 3 fairly incompatible ways of doing it for starters....
>
> Note that R objects are passed-by-value so:
>
> foo = list(a=1,b=2)
> bar = function(z){
> z$a=999
> }
> bar(foo)
>
> will leave foo unchanged.
>
> Barry
>
More information about the R-help
mailing list