I want to add to the above answer. You have to first tell the linux operating system on the instance to allow such a command without a password.
This can be done using the advice found in this other stack exchange quesiton.
If you are using Louis Aslett’s RStudio AMI, from the "terminal" tab in the Rstudio window, run the following code:
sudo visudo
This will open a file that can be editted to change the permission structure.
At the very bottom of the file (scroll down with arrow keys) add the following line:
"rstudio ALL = NOPASSWD: /sbin/shutdown"
Then, to exit press "ctrl + x" and it will prompt you whether you want to save. Press "Y". It will then ask about some options and simply press "Enter"
This should then allow you to run the original solution from an R script or the R console:
system('sudo shutdown -h now', wait = FALSE)
Which will shutdown the system and cause the instance to enter the "Stopped" state on the AWS console.