The Art of R Programming

(WallPaper) #1
Here is another example:

> x <- c(5,2,9,12)
> ifelse(x > 6,2*x,3*x)
[1] 15 6 18 24

We return a vector consisting of the elements ofx, either multiplied by 2 or
3, depending on whether the element is greater than 6.
Again, it helps to think through what is really occurring here. The
expressionx> 6 is a vector of Booleans. If theithcomponent is true, then

theithelement of the return value will be set to theithelement of (^2) x; other-
wise, it will be set to (^3)
x[i], and so on.
The advantage ofifelse()over the standard if-then-else construct is that
it is vectorized, thus potentially much faster.


2.9.1 Extended Example: A Measure of Association.....................


In assessing the statistical relation of two variables, there are many alterna-
tives to the standard correlation measure (Pearson product-moment corre-
lation). Some readers may have heard of the Spearman rank correlation,
for example. These alternative measures have various motivations, such as
robustness tooutliers, which are extreme and possibly erroneous data items.
Here, let’s propose a new such measure, not necessarily for novel sta-
tistical merits (actually it is related to one in broad use, Kendall’sτ), but to
illustrate some of the R programming techniques introduced in this chapter,
especiallyifelse().
Consider vectorsxandy, which are time series, say for measurements
of air temperature and pressure collected once each hour. We’ll define
our measure of association between them to be the fraction of the timex
andyincrease or decrease together—that is, the proportion ofifor which
y[i+1]-y[i]has the same sign asx[i+1]-x[i]. Here is the code:

1 # findud() converts vector v to 1s, 0s, representing an element
2 # increasing or not, relative to the previous one; output length is 1
3 # less than input
4 findud <- function(v) {
5 vud <- v[-1] - v[-length(v)]
6 return(ifelse(vud > 0,1,-1))
7 }
8
9 udcorr <- function(x,y) {
10 ud <- lapply(list(x,y),findud)
11 return(mean(ud[[1]] == ud[[2]]))
12 }


Vectors 49
Free download pdf