Companies do R&D if it’s beneficial, same as hiring staff, same as anything else. Also money spent on R&D is, by definition, not profit.
No business owner sits around with a pile of cash at the end of the year and thinks “Oh I’ve got too much, I’ll spend on R&D for the benefit of humanity”.