如何从另一个 table 中查找值以填充现有的 table 列?

How do I lookup a value from another table to populate existing table column?

我有一个名为 Deals 的数据框,其中一个变量是 $DealYear。这包含 3 个因素(2013 年、2014 年、2015 年)。我在 Deals 中还有一个名为 $GDPDeflator 的专栏,目前尚未填充。例如:

#Deals table 

DealID   DealAmt  DealYear  Name  GDPDeflator   Website
100101    200       2013     ABC        0       www.abc.com
120022    3000      2014     EFG        0       www.efg.com
300012    650       2013     HIJ        0       www.hij.com

我有一个名为 Deflator 的小秒 table,它包含我需要的值 Deals$GDPDeflator:

#Deflator table
Year   Defl
2012   1.10
2013   1.08
2014   1.055
2015   1.046
2016   1.03 

如何根据 Deals$DealYearDeflator$YearDeflator$Defl 中查找 Deals$GDPDeflator 的值?

这是评论中建议的 merge 函数的典型用法。

既然你没有提供minimal reproducible example我得准备一个玩具例子

deals.df <- data.frame(DealID = abs(rnorm(3)),
                       DealYear = c(2013,2014,2015),
                       DealAmt = abs(rnorm(3)))
deflator.df <- data.frame(Year=c(2012:2016),
                          Defl=c(1.1,1.08,1.055,1.046,1.03))

此时您可以在 deals.df 中将 DealYear 重命名为 Year(反之亦然),或者如下所示,使用 by.xby.y 告诉 merge 每个数据框中列的名称

NEW.deals.df <- merge(deals.df, deflator.df, by.x = "DealYear", by.y = "Year")

NEW.deals.df

输出

  DealYear    DealID   DealAmt  Defl
1     2013 2.4428505 0.8423267 1.080
2     2014 0.7864217 1.7308812 1.055
3     2015 1.2319621 0.7857849 1.046

现在您可以根据需要重新排列列。

请注意,您可以使用 by=c("colname1","colname2",...).

匹配具有多个列作为标识符的数据框之间的行