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.

undefined outcomes,” earlier in this chapter, that you have to check whether avalue is missing by using the is.na() function. But you need the values thatare not missing values, so invert the logical vector by preceding it with the !operator. To drop the missing values in the vector x, for example, use thefollowing code:> x[!is.na(x)][1] 3 6 2 1When you’re using R, there’s no way to get around vectorization. After youunderstand how vectorization works, however, you’ll save considerablecalculation time and lines of code.Summarizing logical vectorsYou also can use logical values in arithmetic operations as well. In that case, Rsees TRUE as 1 and FALSE as 0. This allows for some pretty interesting constructs.Suppose that you’re not really interested in finding out the games in whichGranny scored more than Geraldine did, but you want to know how often thathappened. You can use the numerical translation of a logical vector for thatpurpose in the sum() function, as follows:> sum(the.best)[1] 3So, three times, Granny was better than Geraldine. Granny rocks!In addition, you have an easy way to figure out whether any value in a logicalvector is TRUE. Very conveniently, the function that performs that task is calledany(). To ask R whether Granny was better than Geraldine in any game, use thiscode:> any(the.best)[1] TRUEWe told you that Granny rocks! Well, okay, this result is a bit unfair forGeraldine, so you should check whether Granny was better than Geraldine in all thegames. The R function you use for this purpose is called — surprise, surprise —

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

Saved successfully!

Ooh no, something went wrong!