I have a data frame, and I want to do some calculation with existing columns and create new column in my data set which is a combination of existing… I can do this easily outside function… but if I wrap the code witin function, the changes I made (inside functions) are not visible outside function… i.e. the new column doesn’t exist…
I would appreciate sample code to do this…
I’ll assume it is about R… R does not pass arguments by reference (environments and reference classes (S5) are an exception, but this is out of the current range of abstraction). Thus, when you write
yis still 4 at the end of code, because inside the function,xis the fresh copy ofys value, not theyitself (again, not exactly, but those are higher order details).Thus, you must adapt to R’s pass-by-copy scheme and return the altered value and assign it back to your variable (using old wording, there are no procedures in R):
Don’t worry, this works smoothly for even more complex objects because R is garbage-collected and has lazy evaluation.
BTW, you can omit
returnif you want to return the last value produced in function, i.e.addThree‘s definition may look like this: