12.07.2015 Views

R dummies

R dummies

R dummies

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Recycling character vectorsWhen you perform operations on vectors of different lengths, R automaticallyadjusts the length of the shorter vector to match the longer one. This iscalled recycling, since R recycles the element of the shorter vector to createa new vector that matches the original long vector.This feature is very powerful but can lead to confusion if you aren’t aware ofit.The rules for recycling character vectors are exactly the same as for numericvectors (see Chapter 4).Here are a few examples of vector recycling using paste:> paste(c(“A”, “B”), c(1, 2, 3, 4), sep=”-”)[1] “A-1” “B-2” “A-3” “B-4”> paste(c(“A”), c(1, 2, 3, 4, 5), sep=”-”)[1] “A-1” “A-2” “A-3” “A-4” “A-5”See how in the first example A and B get recycled to match the vector oflength four. In the second example, the single A also gets recycled — in thiscase, five times.Because text in R is represented as character vectors, you can sort thesevectors using the same functions as you use with numeric data. For example, to getR to sort the alphabet in reverse, use the sort() function:> sort(letters, decreasing=TRUE)[1] “z” “y” “x” “w” “v” “u” “t” “s” “r” “q” “p”[12] “o” “n” “m” “l” “k” “j” “i” “h” “g” “f” “e”[23] “d” “c” “b” “a”Here you used the decreasing argument of sort().The sort() function sorts a vector. It doesn’t sort the characters of eachelement of the vector. In other words, sort() doesn’t mangle the word itself.You can still read each of the words in words.Try it on your vector words that you created in the previous paragraph:> sort(words)[1] “brown” “DOG” “FOX” “jumps” “lazy”[6] “over” “quick” “the” “The”

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

Saved successfully!

Ooh no, something went wrong!