我有一个带有数以千计的代码的df,用于不同的未来合约.它们有缩写名称(稍后出现)和长名称(我希望在其他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"
)
Run Code Online (Sandbox Code Playgroud)
这个df有我每天收到的列表.我必须去查找缩写名称并将其与长名称匹配.
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"
)
Run Code Online (Sandbox Code Playgroud)
我正在寻找的R要做的是取代$ Symbol列并在full_list $ Ticker列中找到这些值并添加一个列,替换$ Long_Name,其中复制相应的full_list $ Long_Name.希望这是有道理的.我知道列名很难遵循.
这将是一个简单的Excel中的VLookup但我有一个脚本,我将每天使用几乎在R完成.
Jos*_*ich 16
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
Run Code Online (Sandbox Code Playgroud)
你可以使用match- 它给出第一个参数落在第二个参数中的位置的索引.例如:
arg1 <- c("red","blue")
arg2 <- c("blue","red")
> match(arg1,arg2)
[1] 2 1
Run Code Online (Sandbox Code Playgroud)
然后在替换数据框中创建一个新列(注意 - 您应该将其称为其他内容,因为replace实际上是r中的函数),使用带有匹配符号的full_list数据框.
replace$Long_Name <- full_list$Long_Name[match(replace$Symbol,full_list$Ticker)]
> replace
Type Location Symbol Month Long_Name
1 F US BO V13 Soybean Oil -- CBT
2 F US C U13 Corn -- CBT
3 F US DF U13 Dow Jones Industrial Average -- CBT
4 F US AIC U13 DJ UBS Commodity Index -- CBOT
5 F US AC U13 Ethanol -- CBOT
6 F US BBS U13 South American Soybeans -- CBOT
Run Code Online (Sandbox Code Playgroud)
如果它是一个大数据集,您可以从环境查找中受益:
library(qdap)
replace$Long_Name <- lookup(replace$Symbol, full_list)
## > replace
## Type Location Symbol Month Long_Name
## 1 F US BO V13 Soybean Oil -- CBT
## 2 F US C U13 Corn -- CBT
## 3 F US DF U13 Dow Jones Industrial Average -- CBT
## 4 F US AIC U13 DJ UBS Commodity Index -- CBOT
## 5 F US AC U13 Ethanol -- CBOT
## 6 F US BBS U13 South American Soybeans -- CBOT
Run Code Online (Sandbox Code Playgroud)
强制性data.table答案
library(data.table)
full_list <- data.table(full_list, key='Symbol')
replace <- data.table(replace, key='Ticker')
replace[full_list]
Run Code Online (Sandbox Code Playgroud)
FWIW在大约1e5行以上的数据集上键入data.table将明显快于列出的其他方法(除了qdap版本,我没有尝试过).
合并时间可以在这里找到
| 归档时间: |
|
| 查看次数: |
37732 次 |
| 最近记录: |