How to detect if the output of a function is assigned to an object in R

  • A+

Inside an R function, is it possible to detect if the user has assigned the output to an object?

For example, I would like to print on console some information only if the output is not assigned to an object, I am looking for something like this

fun <- function(a){            b <- a^2            if(!<OUTPUT ASSIGNED>) cat('a squared is ', b)            return(invisible(b)) }  

So that the result on console would be different whether the function output is assigned or not, e.g:

> fun(5) > a squared is 25 > > out <- fun(5) > > 


Not sure if I've completely thought this one through, but this seems to work for the example you've given. (Note it's important to use = or assign or .Primitive("<-") inside the fun you'd like to subject to this treatment.)

fun <- function(a){   b = a^2   # can't use <- here   if (!identical(Sys.getenv("R_IS_ASSIGNING"), "true")) cat('a squared is ', b)   return(invisible(b)) }  `<-` <- function(a, b) {   Sys.setenv("R_IS_ASSIGNING" = "true")   eval.parent(substitute(.Primitive("<-")(a, b)))   Sys.unsetenv("R_IS_ASSIGNING") }  fun(5) #> a squared is  25 out <- fun(6) out #> [1] 36 

Created on 2019-02-17 by the reprex package (v0.2.1)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: