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.

Looking at how named vectors workTo illustrate named vectors, take a look at the built-in dataset islands, anamed vector that contains the surface area of the world’s 48 largest land masses(continents and large islands). You can investigate its structure with str(), asfollows:> str(islands)Named num [1:48] 11506 5500 16988 2968 16 ...- attr(*, “names”)= chr [1:48] “Africa” “Antarctica” “Asia” “Australia”...R reports the structure of islands as a named vector with 48 elements. In thefirst line of the results of str(), you see the values of the first few elements ofislands. On the second line, R reports that the named vector has an attributecontaining names and reports that the first few elements are “Africa”,“Antarctica”, “Asia”, and “Australia”.Because each element in the vector has a value as well as a name, now youcan subset the vector by name. To retrieve the sizes of Asia, Africa, and Antarctica,use the following:> islands[c(“Asia”, “Africa”, “Antarctica”)]Asia Africa Antarctica16988 11506 5500You use the names() function to retrieve the names in a named vector:> names(islands)[1:9][1] “Africa” “Antarctica” “Asia”[4] “Australia” “Axel Heiberg” “Baffin”[7] “Banks” “Borneo” “Britain”This function allows you to do all kinds of interesting things. Imagine youwanted to know the names of the six largest islands. To do this, you would retrievethe names of islands after sorting it in decreasing order:> names(sort(islands, decreasing=TRUE)[1:6])[1] “Asia” “Africa” “North America”[4] “South America” “Antarctica” “Europe”

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

Saved successfully!

Ooh no, something went wrong!