Tomaz Kastrun has a script to check and install missing packages in SQL Server R Services code:
Result in this case will be successful with correct R results and sp_execute_external_script will not return error for missing libraries.
I added a “fake” library called test123 for testing purposes if all the libraries will be installed successfully.
At the end the script generated xp_cmdshell command (in one line)
This is a rather clever solution to a problem which I’d rather not exist. There really ought to be a better way for authorized users programmatically to install packages.