What few people know about R4-P17 is that after her decapitation in ROTS, her head landed in Mos Eisley. A kindly repair shop owner fixed her and put her head onto a new blue body. She had been working faithfully for the repair shop owner for awhile since then.
Just before the Millenium Falcon blasted off from Mos Eisley, R4 and a newly-repaired Skippy the Jedi Droid fell in love, and were subsequently captured by the Empire. They were both sent to the Death Star, and were scheduled to be checked for the stolen plans. However, once the Empire found out that the technical readouts were not in Skippy or R4, they were scheduled to be terminated. Skippy managed to escape and free R4 as well, but that was not until the Battle of Yavin had begun. The two droids would've been destroyed with the Death Star, had they not stowed away aboard Tag and Bink's hijacked shuttle.
The two droids, being more competent than Tag and Bink, were able to find the Rebels on Hoth a few months before Tag and Bink arrived at Bespin. R4 was assigned to repair the Millennium Falcon, though the task was so great that it required her personality to be transferred to a treadwell droid in order to more effectively repair it. She was re-transferred to her own body after the evacuation.
R4 and Skippy were married right before the Battle of Endor. During the battle, Skippy was destroyed. R4 was greatly depressed when that happened, but her spirits brightened when, after the battle, she found that, among the force ghosts standing and watching the celebration was: Sebastian Shaw's Anakin Skywalker!!! Oh, and Skippy was there, too, but yeah, whatever. By that point, she already started hanging out with R2-D2...