[R] (no subject)

David Winsemius dwinsemius at comcast.net
Wed Sep 7 17:19:22 CEST 2011


On Sep 7, 2011, at 6:04 AM, Varsha Agrawal wrote:

> The code looks like this:
> L1=list(a=1,b=2,c=3)
> f1=as.factor(c)
> L1[[f1]] returns 1
>
> What happens if we give a factor as an index at a list?

In a virgin session of R there would be no 'c' for the second line to  
work with. And since 'c' is a function you would probably get an error.

 > L1=list(a=1,b=2,c=3)
 > f1=as.factor(L1$c)
 > f1
[1] 3
Levels: 3
 > L1[[f1]] #returns 1
[1] 1

It is ill-mannered to attach an object and not tell us that was done.  
So why is "3" as an index returning 1? because the internal  
representation of a factor was used by the parser. Furthermore even  
the usual dodge of wrapping as.character around f1 will not succeed  
since f1 didn't record where it got the value of "3", and there is no  
L1["3"] or L1[["3"]] only an L1[[3]] and an L1[3]

 > L1[[as.character(f1)]]
NULL

So you need the "full-court [factor] press":

 > L1[[as.numeric(as.character(f1))]]
[1] 3



>
> 	[[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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list