循环并比较R

时间:2015-09-16 16:57:14

标签: r dataframe

我需要循环使用2个数据帧。

Df1[1:5,]

  year month      Vol
1 2015     7 4.82e-05
2 2015     6 5.91e-05
3 2015     5 6.56e-05
4 2015     4 6.10e-05
5 2015     3 7.85e-05

Df2[1:5,]

  year month IB
1 2015     7  0
2 2015     4  1
3 2015     3  0
4 2015     6  1
5 2015     5  0

我需要循环浏览DF1,比较DF1DF2的月份,如果它们相同,则设置DF1$IB<-DF2$IB。我尝试使用sapply,但我收到此错误

tmp<-sapply(DF1$month,function(x){if(DF2$month==x){
DF1$IB<-DF2$IB
}})

Warning messages:
1: In if (DF2$month == x) { :
  the condition has length > 1 and only the first element will be used
.....

非常感谢任何帮助。否则我将不得不求助于多个for循环,并且因为DF1长900K行而DF2长300行,这对我来说似乎效率很低。

2 个答案:

答案 0 :(得分:3)

如果你的Df1是大数据。表可能比合并更好。

library(data.table)
setkey(setDT(Df1),year,month)[setDT(Df2),IB:=IB]
Df1
#    year month      Vol IB
# 1: 2015     3 7.85e-05  0
# 2: 2015     4 6.10e-05  1
# 3: 2015     5 6.56e-05  0
# 4: 2015     6 5.91e-05  1
# 5: 2015     7 4.82e-05  0

因此,这会将Df1转换为年份和月份的索引中的data.table,然后在Df2上执行data.table连接(也转换为data.table),然后添加从IBDf2的{​​{1}}列。

使用更现实的例子:

Df1

答案 1 :(得分:3)

使用最新版本(see here how to install v1.9.5 from GH),您不需要设置密钥,只需要添加setDT(df1)[df2, on = c("year","month")]的{​​{1}},即可:

IB

假设两个数据集的 year month Vol IB 1: 2015 7 4.82e-05 0 2: 2015 4 6.10e-05 1 3: 2015 3 7.85e-05 0 4: 2015 6 5.91e-05 1 5: 2015 5 6.56e-05 0 / year不相等,则必须以不同方式加入:

month

给出:

setDT(df2)[df1, on = c("year","month")]

第二个例子的已用数据:

   year month IB      Vol
1: 2015     7  0 4.82e-05
2: 2015     6  1 5.91e-05
3: 2015     5  0 6.56e-05
4: 2015     4  1 6.10e-05
5: 2015     3 NA 7.85e-05
相关问题