Is this expected behaviour? x <- factor(c("c", "b", "a","c")) results <- c(c=4, b=5) results[x] giving > results[x] <NA> b c <NA> NA 5 4 NA (i.e. it appears to give results[levels(x)] whereas results[as.character(x)] does what I expected: as.character(x) results[as.character(x)] > as.character(x) [1] "c" "b" "a" "c" > results[as.character(x)] c b <NA> c 4 5 NA 4 Duncan Murdoch
On Wed, May 26, 2010 at 3:27 PM, Duncan Murdoch <murdoch.duncan at gmail.com> wrote:> Is this expected behaviour? > > x <- factor(c("c", "b", "a","c")) > results <- c(c=4, b=5) > results[x] > > giving > >> results[x] > <NA> ? ?b ? ?c <NA> > ?NA ? ?5 ? ?4 ? NA > > (i.e. it appears to give results[levels(x)]I would say it gives results[as.numeric(x)] and it's not clear if that is less "expected". E.g., what happens if results has no names? results[as.numeric(x)] would still work, but not results[as.character(x)]. Factors have a dual nature (character labels vs numeric codes), and when forced to choose, I think it's reasonable to choose the solution which works more generally. -Deepayan> > > whereas results[as.character(x)] does what I expected: > > as.character(x) > results[as.character(x)] > >> as.character(x) > [1] "c" "b" "a" "c" >> results[as.character(x)] > ?c ? ?b <NA> ? ?c > ?4 ? ?5 ? NA ? ?4 > > Duncan Murdoch > > ______________________________________________ > R-devel at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-devel >
G'day Duncan, On Wed, 26 May 2010 05:57:38 -0400 Duncan Murdoch <murdoch.duncan at gmail.com> wrote:> Is this expected behaviour?Yes, according to the answer that this poster https://stat.ethz.ch/pipermail/r-devel/2008-March/048674.html got. Indeed, the help page of '[' states: The index object i can be numeric, logical, character or empty. Indexing by factors is allowed and is equivalent to indexing by the numeric codes (see factor) and not by the character values which are printed (for which use [as.character(i)]). Cheers, Berwin
Duncan Murdoch wrote:> Is this expected behaviour? > > x <- factor(c("c", "b", "a","c")) > results <- c(c=4, b=5) > results[x] > > giving > > > results[x] > <NA> b c <NA> > NA 5 4 NA > > (i.e. it appears to give results[levels(x)] >Thanks to all for pointing out my misinterpretation. It's clearly not a bug. Duncan Murdoch> > whereas results[as.character(x)] does what I expected: > > as.character(x) > results[as.character(x)] > > > as.character(x) > [1] "c" "b" "a" "c" > > results[as.character(x)] > c b <NA> c > 4 5 NA 4 > > Duncan Murdoch >