get the name of the output variable in R -
sorry poor english
is there way in r name used returning values of function within function, same way can grab name of input variables "substitute"??. mean "outputname" function:
myfun=function(x){ namein=substitute(x) nameout=outputname() out=x*2 cat("the name of input ", namein," , value:\n") print(x) cat("the name of output ", nameout, "and value:\n") print(out) return(out) } this wish:
> myinput=12; > myoutput=myfun(myinput) name of input myinput , value: [1] 12 name of output myoutput , value: [1] 24 > myoutput [1] 24 i've been looking reply , going crazy. seems simple can't find anything.
thanks
here 2 workarounds comments. first uses environments pass reference. output variable supplied argument myfun1. sec uses assign assign homecoming value of myfun2 output variable , retrieves name of ouput variable examining phone call stack.
myinput <- 12 workaround 1
myfun1 <- function(x, output){ namein=substitute(x) nameout=substitute(output) output$value=x*2 cat("the name of input ", namein," , value:\n") print(x) cat("the name of output ", nameout, "and value:\n") print(output$value) } myoutput <- new.env() myoutput$value <- 1 myfun1(myinput, myoutput) # name of input myinput , value: # [1] 12 # name of output myoutput , value: # [1] 24 myoutput$value # [1] 24 workaround 2
suggested @roland (my interpretation of comment, @ least):
myfun2=function(x){ namein=substitute(x) nameout=as.list(sys.calls()[[1]])[[2]] out=x*2 cat("the name of input ", namein," , value:\n") print(x) cat("the name of output ", nameout, "and value:\n") print(out) return(out) } assign('myoutput', myfun2(myinput)) # name of input myinput , value: # [1] 12 # name of output myoutput , value: # [1] 24 myoutput # [1] 24 r
No comments:
Post a Comment