Anatolye Anatolye - 2 months ago 5
R Question

R: addition value from one table to another by date (join the tables)

Good day! Please help me!
I'm going to add value "Open" from table "D"("xts" "zoo") to table "d"("data.frame") by date ("index" in "D", "dateOpen" in "d"). I want to add a new column to "d" with the corresponding date. How can I do this with R?

Thank you!

"d"
dateOpen priceOpen dateClose priceClose res cumres
1 2016-01-13 11:55:00 70670 2016-01-13 12:46:00 69853 -817 -817
2 2016-01-13 16:20:00 70670 2016-01-13 18:31:00 69853 -817 -1634
3 2016-01-14 21:55:00 70090 2016-01-14 23:49:00 69940 -150 -1784

"D"
Open High Low Close Volume
2016-01-11 16811 73560 68230 68710 656176
2016-01-12 68700 70720 67800 69050 766788
2016-01-13 69130 70930 68140 68470 798137
2016-01-14 68420 70220 67980 70060 757285
2016-01-15 69970 69970 64020 64970 1147526




The answer is:
dateOpen priceOpen dateClose priceClose res cumres Open
1 2016-01-13 11:55:00 70670 2016-01-13 12:46:00 69853 -817 -817 69130
2 2016-01-13 16:20:00 70670 2016-01-13 18:31:00 69853 -817 -1634 69130
3 2016-01-14 21:55:00 70090 2016-01-14 23:49:00 69940 -150 -1784 68420

Answer

Use the merge function.

df <- merge(d,
            D[, c("index", "Open")],
            by.x = "dateOpen",
            by.y = "index")

This assumes your date column in D is named "index", that part was a bit unclear in your question.

Comments