[英]R How to update a column in data.frame using values from another data.frame
New to R. I have a data.frame R.的新手。我有一个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 以及一个名为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. 我想找到一种方法来更新数据框“级别”列,方法是在查找列表中查找值,将数据框“score”列与查找列表中的数字名称相匹配。 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
):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.