简体   繁体   中英

R How to update a column in data.frame using values from another data.frame

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM