我正在尝试根据某些标准将市场数据集(997 个对象的长度)中的值分配给另一个 (t_final) 数据集(680 个对象的长度)。
market_dt 由列组成:ref.date 和 ret.closure.prices t_final 由列组成:日期和化合物
两个数据集都有相同格式的日期 YYYY-MM-DD
我想让一个循环这样工作(见下文),如果日期匹配,我的 ret.closure.prices 值将被复制到 t_final 数据集中的新列。
for i in 1:997 {
if (market_dt[]$ref.date == t_final[]$date){
t_final[]$return <- market_dt[]$ret.closing.prices
}
但是我得到了错误:
Warning messages:
1: In `==.default`(market_dt[]$ref.date, t_final[]$date) :
longer object length is not a multiple of shorter object length
2: In if (market_dt[]$ref.date == t_final[]$date) { :
the condition has length > 1 and only the first element will be used
我怎样才能正确地完成这项工作?
谢谢!
答案 0 :(得分:1)
您可以使用“加入”功能:
library(dplyr)
left_join(t_final, market_dt, by = c("date" = "ref.date")) %>%
rename(return = ret.closing.prices)