[R] Unexpected behavior when browsing list objects by name, when the object name is a substring (prefix) of an existing object that has a valid value

R. Michael Weylandt michael.weylandt at gmail.com
Tue Nov 8 13:12:01 CET 2011


You've stumbled on one of the reasons use of the $ operator is
discouraged in formal programming: it uses partial matching when given
names.

E.g.,

a = list(boy = 1:5, cat = 1:10, dog = 1:3)

a$d #Exists

If you want to require exact matching (and it seems you do), use the
[[ operator.

a[["d"]] # Error
a[["dog"]] # Works
a[["alligator"]] <- 1:100  #Works

Michael

On Tue, Nov 8, 2011 at 12:29 AM, Val Athaide <vathaid at gmail.com> wrote:
>>
>> Hi,
>>
>> The program I am writing requires me to append named objects to my
>> existing list objects dynamically.
>>
>> So my list object is retval. retval always has a metadatatabletype object
>>
>> createMetadata=TRUE
>> retval <-list()
>> retval$metadatatype =c("normal")
>> retval$metadata=NULL
>>
>> How, depending on certain logic, I create a metadata object
>>
>> if (createMetadata==TRUE) retval$metadata =rbind(retval$metadata,c(1,0) )
>> The results are
>> > retval$metadata
>>      [,1]     [,2]
>> [1,] "normal" "normal"
>> [2,] "1"      "0"
>>
>>
>> What I expected to see is
>> > retval$metadata
>>      [,1]     [,2]
>> [1,] "1"      "0"
>>
>>
>>
>> I have been able to reproduce this problem only when the object
>> retval$metadata is NULL and there is an existing object that has a valid
>> value and the NULL object is a sub-string (prefix) of the existing object
>> with a valid value.
>>
>> Also, retval$metadata takes on a value of "normal" even though it has been
>> explicity set as NULL
>>
>> Your assistance is appreciated.
>>
>> Thanks
>> Vathaid
>>
>>
>>
>>
>
>        [[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