12.07.2015 Views

R dummies

R dummies

R dummies

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

There’s no way you can define in the argument list that x should be anumeric vector. For example, if you try to use a character vector as a value forx, the multiplication inside the body will throw an error because you can’tmultiply characters by a number. If you want to control which type of object isgiven as an argument, you have to do so manually, in the body of the function.(We give examples of that in Chapters 9 and 10.)Using the functionSave 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 byitself that it loaded the function, but it’s there in the workspace, as you can checkby using ls():> ls()[1] “addPercent” “percent” “result” “x”If you create a function and load it in the workspace by sourcing the scriptcontaining the function, this function becomes an object in the workspace andcan, thus, be found using ls() and — if necessary — removed using rm().Formatting the numbersThe output of ls() tells you the function is there, so you should be able to useit. You can now create the most astonishing percentages by using theaddPercent() function like this:> new.numbers addPercent(new.numbers)[1] “82.2%” “2.5%” “162%” “40%”Actually, you could use the code sprintf(“%1.1f%%”,100*x) instead of theaddPercent() function for a very similar result. C coders will recognizesprintf() immediately and agree that it’s both incredibly versatile and

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!