It sometimes works? That's a good sign, it's probably just dirty inside.
Start by [guide|98065|taking the bottom case off|new_window=true] so you can access the actual buttons. Then dip a q-tip in isopropyl alcohol (90% or higher), hold the ds so the hinge faces up, and use the wet qtip to press the R button a bunch of times. The goal is to get alcohol down inside the button, so a dripping qtip is probably best
I haven't had a reason to do this on a 2ds yet, but it's worked for me with ds lites. Normally I'd go with no fewer than ~30 presses, but you can just pop the battery back in and test it without reassembling everything
If that doesn't work, the button probably needs to be replaced.