Vim: Compute this in R

Published: 2021-03-23T21:00:00.000Z

Often when working with numbers in code I need to convert them into some different format. Just opening an R REPL and running the calculation there is great. But it quickly becomes annoying when you have to do it on a whole list of numbers.

After bumping into this annoyance a few times I wrote myself a simple solution. A key mapping that computes whatever is in the visual selection in R and inserts the result in its place.

vnoremap <script> <silent> R dm':read !Rscript -e '<C-R>"'<CR>df<Space>d$i<Backspace><Esc><C-o>""P

With this key mapping in you .vimrc you can now simply write out some calculation you want to make (say sqrt(256) or 1 + 1), select it in visual mode (type v end move so that the calculation is marked) and press R.