The function documentSave() or documentSaveAll() in the package
rstudioapi is used to save the R script. Note that R scripts need to
have a file location before this function can be used.
References
Ushey, K., Allaire, J., Wickham, H., & Ritchie, G. (2022). rstudioapi: Safely
access the RStudio API. R package version 0.14.
https://CRAN.R-project.org/package=rstudioapi