Once you have created and transformed a script in R, save the script again, and load it into the console using the source() command displayed earlier. Now you see . . . nothing. R doesn’t let you know by itself that it loaded the function, but it’s there in the workspace, as you can check by using ls():

> ls()
[1] "addPercent" "percent"    "result"    "x"

If you create a function and load it in the workspace by sourcing the script containing the function, this function becomes an object in the workspace and can, thus, be found using ls() and — if necessary — removed using rm().

Format the numbers in R

The output of ls() tells you the function is there, so you should be able to use it. You can now create the most astonishing percentages by using the addPercent() function like this:

> new.numbers <- c(0.8223, 0.02487, 1.62, 0.4)
> addPercent(new.numbers)

Actually, you could use the code sprintf("%1.1f%%",100*x) instead of the addPercent() function for a very similar result. C coders will recognize sprintf() immediately and agree that it’s both incredibly versatile and complex. The function comes with a very long Help page that’s definitely worth reading if you need to format values often. If not, save yourself the headache.

Play with R function objects

Because a function in R is just another object, you can manipulate it much the same way as you manipulate other objects. You can assign the function to a new object and effectively copy it like this:

> ppaste <- addPercent

Now ppaste is a function as well that does exactly the same as addPercent. Note that you don’t add parentheses after addPercent in this case.

If you add the parentheses, you call the function and put the result of that call in ppaste. If you don’t add the parentheses, you refer to the function object itself without calling it. This difference is important when you use functions as arguments.

You can print the content of a function by simply typing its name at the prompt, like this:

> ppaste
 result <- paste(percent, "%", sep = "")

So, the assignment to ppaste actually copied the function code of addPercent into a new object.

That’s all cool, but it also means that you can effectively erase a function if you accidentally use the same name for another object. Or you could lose data if you accidentally gave the same name as your data object to a function. There’s no undo button in R, so pay attention to the names you choose.

Luckily, this problem doesn’t occur with the base R functions and functions contained in packages. Although it’s not a good idea, you could, for example, name a vector sum and still be able to use the sum() function afterward. When you use sum() as a function, R only searches for functions with that name and disregards all other objects with the same name.