If in RStudio I do
suma=4+5
The sum variable is saved, normally in a small window to the right, in a category called Values.
If I do for example:
sum<- function(d1,d2) {
suma=d1+d2
mul=suma*9
cat(paste0("El resultado es:", mul))
}
sum(4,5)
I get the result, and the function is saved, but it is not saved visually suma
or mul
in the little window.
How can I modify the function so that sum is saved so that I can access its result from the values window?
Modify the function so that at the end it returns the value by adding return(mul) or simply mul.
Save the value of the sum() function in a variable:
Variables in R are always associated with an "environment", which are like "boxes" where one stores things, normally symbols that represent variable or function names, important: they do not store the data but the name or reference to the data. Another important thing is that each environment stores the reference to its "parent" environment.
The panel you mention is precisely the environment inspection panel, in fact the tab is called "Environment", and by default the "Global Environment" is shown, which would be the initial environment of the Script you have open. Now each function instantiates its own private and temporary environment, all local variables are created in this environment and it is destroyed when the function exits and therefore you will never see the values of these variables after the function exits, eventually yes, but in case you were doing an interactive "debug", when you go step by step through the function code you will be able to see the "local environment" and see these variables.
It makes little sense, but if you wanted to see the values of these "local" variables, what you can do is transform them into "parent" environment variables, this is achieved by assigning the values with
<<-
, for example:As
<<-
longsuma
asmul
they are not created in the local environment, but in the parent or global environment in this case, so you should already see the values in the global environment panel, but this is not a good practice, it is preferable that the variables of a function are truly local.With respect to:
They have already given you an adequate answer, you have to return the value, which can be done simply by placing the name of the variable as the last instruction of the function, or else making an
return()
explicit one.