This question already has answers here:
How to do vlookup and fill down (like in Excel) in R?

(9个答案)


7年前关闭。




我有一个包含数千种股票的df,用于不同的 future 合约。它们具有缩写名称(稍后出现)和长名称(我想在其他df中使用)
full_list <- structure(
  list(
    Ticker = c("AC", "AIC", "BBS", "BO", "C", "DF"),
    Long_Name = c("Ethanol -- CBOT", "DJ UBS Commodity Index -- CBOT", "South American Soybeans -- CBOT", "Soybean Oil -- CBT", "Corn -- CBT", "Dow Jones Industrial Average -- CBT")
  ),
  .Names = c("Ticker", "Long_Name"),
  row.names = c(NA, 6L),
  class = "data.frame"
)

这个df有我每天收到的 list 。我必须去查找缩写名称并将其与长名称匹配。
replace <- structure(
  list(
    Type = c("F", "F", "F", "F", "F", "F"),
    Location = c("US", "US", "US", "US", "US", "US"),
    Symbol = c("BO", "C", "DF", "AIC", "AC", "BBS"),
    Month = c("V13", "U13", "U13", "U13", "U13", "U13")
  ),
  .Names = c("Type", "Location", "Symbol", "Month"),
  row.names = c(NA, 6L),
  class = "data.frame"
)

我正在寻找R要做的是获取replace $ Symbol列,并在full_list $ Ticker列中找到这些值,然后添加一列replace $ Long_Name,将相应的full_list $ Long_Name复制到其中。希望这是有道理的。我知道列名很难理解。

这在excel中是很容易的VLookup,但是我有一个脚本,几乎每天都会在R中使用。

最佳答案

merge他们:

> merge(full_list, replace, by.x="Ticker", by.y="Symbol")
  Ticker                           Long_Name Type Location Month
1     AC                     Ethanol -- CBOT    F       US   U13
2    AIC      DJ UBS Commodity Index -- CBOT    F       US   U13
3    BBS     South American Soybeans -- CBOT    F       US   U13
4     BO                  Soybean Oil -- CBT    F       US   V13
5      C                         Corn -- CBT    F       US   U13
6     DF Dow Jones Industrial Average -- CBT    F       US   U13

关于r - R中的VLookup类型方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18645222/

10-12 14:02