u
[1]167235
diff(u)
[1]51-512
Then line 5 in the preceding example would become this:
vud <- diff(d)
We can make the code really compact by using another advanced R
function,sign(), which converts the numbers in its argument vector to 1,
0, or−1, depending on whether they are positive, zero, or negative. Here
is an example:
u
[1]167235
diff(u)
[1]51-512
sign(diff(u))
[1]11-111
Usingsign()then allows us to turn thisudcorr()function into a one-liner,
as follows:
udcorr <- function(x,y) mean(sign(diff(x)) == sign(diff(y)))
This is certainly a lot shorter than the original version. But is it better?
For most people, it probably would take longer to write. And although the
code is short, it is arguably harder to understand.
All R programmers must find their own “happy medium” in trading
brevity for clarity.
2.9.2 Extended Example: Recoding an Abalone Data Set................
Due to the vector nature of the arguments, you can nestifelse()opera-
tions. In the following example, which involves an abalone data set, gender
is coded as M, F, or I (for infant). We wish to recode those characters as 1, 2,
or 3. The real data set consists of more than 4,000 observations, but for our
example, we’ll say we have just a few, stored ing:
g
[1] "M" "F" "F" "I" "M" "M" "F"
ifelse(g == "M",1,ifelse(g == "F",2,3))
[1]1223112
Vectors 51