简体   繁体   English

使用 R 中的两列值快速查找另一个数据框

[英]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.

相关问题 R使用查找表使用查找的列名更新数据框中的零值 - R update zero values in a data frame using a lookup table using the column names for the lookup 使用来自另一个data.frame的查找值更新data.frame中的列-带有子字符串匹配 - Updating a column in data.frame using lookup values from another data.frame - with substring matching R 使用另一个列中的值索引数据框 - R indexing a data frame using values in the column of another R中的计算列以及从另一个数据帧中查找 - Calculated column in R with lookup from another data frame 数据框 R - 查找字符串的一部分并返回某些两个值 - Data frame R - lookup for the part of the string and return certain two values 使用一个data.frame中的数据为R中另一个data.frame中的新列生成值 - Using data in one data.frame to generate values for a new column in another data.frame in R 使用r中另一数据帧中的两列对一个数据帧中的列进行子集 - Subseting column in one data frame using two columns in another data frame in r R如何使用另一个data.frame中的值更新data.frame中的列 - R How to update a column in data.frame using values from another data.frame 如何使用 R 中另一个数据帧中包含的值对数据帧的列进行计算? - How to do calculations on a column of a data frame using values contained in another data frame in R? R-使用查找表替换数据框中的值 - R - replace values in data frame using lookup table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM