Skip to content
Prev 309191 / 398506 Next

using match-type function to return correctly ordered data from a dataframe

Is the following what you want?

  > dfLETTERS <- data.frame(LETTER=LETTERS[1:5], lData=c("Ay","Bee","Cee","Dee","Eee"), row.names=sprintf("LRow%d",1:5))
  > z <- c("D", "B", "A", "B")
  > dfLETTERS[match(z, dfLETTERS$LETTER), ]
          LETTER lData
  LRow4        D   Dee
  LRow2        B   Bee
  LRow1        A    Ay
  LRow2.1      B   Bee
  > # or when z includes things not in the list to match:
  > dfLETTERS[match(c("E",NA,"notALetter","A"), dfLETTERS$LETTER), ]
        LETTER lData
  LRow5      E   Eee
  NA      <NA>  <NA>
  NA.1    <NA>  <NA>
  LRow1      A    Ay

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com