Saving `sessionInfo()` as a .txt file

Hi, I need some help in finding an easier/automated way of saving my sessionInfo() for my R scripts.

At present, I have saved a code snippet that I use at the start of any new R script where i change the file path of the session info manually.

	# Script info-------------------------------------------------------------------
	# 
	# Title: 
	# Subtitle: 
	# Description: 
	#   
	# Author:
	# Email: 
	# 
	# Date: `r format(Sys.Date(),'%d %B %Y')`
	# 
	# ------------------------------------------------------------------------------
		
	# Install Packages & Load Libraries ----

	# Working Script ---------------------------------------------------------------
	
	# Session Info -----------------------------------------------------------------
	
	session_info <- sessionInfo()
	capture.output(session_info, file="session_info.txt")

I would like to know if I can preset the file path in the saved snippet more specific to the R script so that every time I use the code snippet, the file path to save the session info contains the name of the R script.

For example, if I am working on different files

  1. data_cleaning.R
  2. regression_model.R

I would like my code snippet to create a file path for the corresponding script files like below so there is no need to change it manually for every script

1. capture.output(session_info, file="data_cleaning_session_info.txt")
2. capture.output(session_info, file="regression_model_session_info.txt")

Key is to retrieve Rscript's filename in R, though many package can do this work, I'd like to offer a lightweight solution. Try

library(stringr)

fname <- rstudioapi::getActiveDocumentContext()$path |> str_extract("(?<=/)[^/]+(?=\\.R)")

capture.output(sessionInfo(), file = str_glue("./{fname}_session_info.txt"))

1 Like

Thanks for the help. It works

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.