[英]Quickly lookup to another data frame using two column values in R
I have a data frame (call it 'ModelOutput') with three columns (Trial, DurationRet, DiscountRate) and another (call it 'drdata') with three columns (Scenario, variable, value).我有一个包含三列(Trial、DurationRet、DiscountRate)的数据框(称为“ModelOutput”)和另一个包含三列(场景、变量、值)的数据框(称为“drdata”)。
I want to quickly filter drdata$Scenario == ModelOutput$Trial & drdata$variable == ModelOutput$DurationRet to return drdata$value into the ModelOutput$DiscountRate column.我想快速过滤 drdata$Scenario == ModelOutput$Trial & drdata$variable == ModelOutput$DurationRet 以将 drdata$value 返回到 ModelOutput$DiscountRate 列。 Is there a way to do this efficiently?
有没有办法有效地做到这一点?
Here are my two attempts, the first of which fails and the second of which is entirely too slow.这是我的两次尝试,第一次失败了,第二次太慢了。
ModelOutput$Trial <- drdata[drdata$Scenario == ModelOutput$Trial & drdata$variable == ModelOutput$DurationRet,"value"]
foreach(row = 1:nrow(ModelOutput)) %do%{
ModelOutput[row, "DiscountRate"] <- drdata[drdata$Scenario == ModelOutput[row, "Trial"] & drdata$variable == as.factor(ModelOutput[row,"DurationRet"]+1),"value"]
}
It took me a minute, but I realized joins could do the job I was looking for.我花了一分钟,但我意识到加入可以完成我正在寻找的工作。
Here is my final code:这是我的最终代码:
ModelOutput <- ModelOutput %>% full_join(drdata, by = c(Trial = "Scenario", DurationRet = "variable"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.