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.

Vectorizing your functionsVectorized functions are a very useful feature of R, but programmers who areused to other languages often have trouble with this concept at first. A vectorizedfunction works not just on a single value, but on a whole vector of values at thesame time. Your natural reflex as a programmer may be to loop over all values ofthe vector and apply the function, but vectorization makes that unnecessary. Trustus: When you start using vectorization in R, it’ll help simplify your code.To try vectorized functions, you have to make a vector. You do this by usingthe c() function, which stands for concatenate. The actual values are separated bycommas.Here’s an example: Suppose that Granny plays basketball with her friendGeraldine, and you keep a score of Granny’s number of baskets in each game. Aftersix games, you want to know how many baskets Granny has made so far thisseason. You can put these numbers in a vector, like this:> baskets.of.Granny baskets.of.Granny[1] 12 4 4 6 9 3To find the total number of baskets Granny made, you just type the following:> sum(baskets.of.Granny)[1] 38You could get the same result by going over the vector number by number,adding each new number to the sum of the previous numbers, but that methodwould require you to write more code and it would take longer to calculate. Youwon’t notice it on just six numbers, but the difference will be obvious when youhave to sum a few thousand of them.In this example of vectorization, a function uses the complete vector to giveyou one result. Granted, this example is trivial (you may have guessed that sum()would accomplish the same goal), but for other functions in R, the vectorizationmay be less obvious.A less obvious example of a vectorized function is the paste() function. If youmake a vector with the first names of the members of your family, paste() can add

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

Saved successfully!

Ooh no, something went wrong!