0

New to R. I have a data.frame

'data.frame':   2070 obs. of  5 variables:
 $ id   : int  16625062 16711130 16625064 16668358 16625066 16711227 16711290 16668746     16711502 16625494 ...
 $ subj : Factor w/ 3 levels "L","M","S": 1 1 1 1 1 1 1 1 1 1 ...
 $ grade: int  4 6 4 5 4 6 6 5 6 4 ...
 $ score: int  225 225 0 225 225 375 375 125 225 125 ...
 $ level: logi  NA NA NA NA NA NA ...

and a list of named numbers called lookup

 Named num [1:12] 12 19 20 26 31 32 49 67 72 73 ...
 - attr(*, "names")= chr [1:12] "0" "50" "100" "125" ...

I'd like to find a way to update the data frame "level" column by looking up values in the lookup list, matching the data frame "score" column with the name of the number in the lookup list. In other words, the score values in the data frame are used to lookup the number (that will go in the level column) in the lookup list.

So... if anyone understands what I mean... please help.

Thanks Robn

RobN
  • 1
  • 1
  • 1
  • 4
    Welcome to StackOverflow! In general, it's a good idea to provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), for example by using `dput` on a subset of your data frame and posting the results. – David Robinson Sep 14 '12 at 15:00
  • Good info on using dput for this. Thanks! (I added comment, since if I just upvote your comment, it's not clear what I'm upvoting). – Hugh Perkins Oct 22 '12 at 06:31

1 Answers1

2

You should be able to do this with (assuming your data frame is called d):

d$level = as.numeric(lookup[as.character(d$score)])

For example:

lookup = list(1, 2, 3, 4)
names(lookup) = c("0", "50", "100", "150")

d = data.frame(score=c(50, 150, 0, 0), level=NA)
d$level = as.numeric(lookup[as.character(d$score)])
print(d)
#   score level
# 1    50     2
# 2   150     4
# 3     0     1
# 4     0     1
David Robinson
  • 77,383
  • 16
  • 167
  • 187