reg.finalizer package:base R Documentation _F_i_n_a_l_i_z_a_t_i_o_n _o_f _O_b_j_e_c_t_s _D_e_s_c_r_i_p_t_i_o_n: Registers an R function to be called upon garbage collection of object or (optionally) at the end of an R session. _U_s_a_g_e: reg.finalizer(e, f, onexit = FALSE) _A_r_g_u_m_e_n_t_s: e: Object to finalize. Must be environment or external pointer. f: Function to call on finalization. Must accept a single argument, which will be the object to finalize. onexit: logical: should the finalizer be run if the object is still uncollected at the end of the R session? _V_a_l_u_e: 'NULL'. _N_o_t_e: The purpose of this function is mainly to allow objects that refer to external items (a temporary file, say) to perform cleanup actions when they are no longer referenced from within R. This only makes sense for objects that are never copied on assignment, hence the restriction to environments and external pointers. _S_e_e _A_l_s_o: 'gc' and 'Memory' for garbage collection and memory management. _E_x_a_m_p_l_e_s: f <- function(e) print("cleaning....") g <- function(x){ e <- environment(); reg.finalizer(e,f) } g() invisible(gc()) # trigger cleanup