10.07.2015 Views

Using R for Introductory Statistics : John Verzani

Using R for Introductory Statistics : John Verzani

Using R for Introductory Statistics : John Verzani

SHOW MORE
SHOW LESS

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

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

<strong>Using</strong> R <strong>for</strong> introductory statistics 161.3 Accessing data by using indices<strong>Using</strong> R to access the entries in a data vector is straight<strong>for</strong>ward. Each observation, x 1 , x 2 ,…, x n , is referred to by its index using square brackets, as in x [1], x [2], …, x [n]. <strong>Using</strong>the indices, we can access and assign to the values stored in the data vector.We keep track of eBay’s Friday stock price in the variable ebay. The first two monthsof data are88.8 88.3 90.2 93.5 95.2 94.7 99.2 99.4 101.6These are entered as> ebay = c(88.8, 88.3, 90.2, 93.5, 95.2, 94.7, 99.2,99.4, 101.6)> length(ebay)[1] 9The first value is clearly 88.8 and the last 101.6. We can get these directly, as in> ebay[1][1] 88.8> ebay[9][1] 101.6> ebay[length(ebay)] # in case length isn’tknown[1] 101.6Slicing R also allows slicing, or taking more than one entry at a time. If x is the datavector, and vec is a vector of positive indices, then x [vec] is a new vector correspondingto those indices. For the ebay example, the first four entries are <strong>for</strong> the first month. Theycan be found by> ebay[1:4][1] 88.8 88.3 90.2 93.5The first, fifth, and ninth Fridays can be accessed using c (1, 5, 9) as the index.> ebay[c(1,5,9)][1] 88.8 95.2 101.6Negative indices If the index in x [i] is positive, we can intuit the result. The ith value ofx is returned if i is between 1 and n. If i is bigger than n, a value of NA is returned,indicating “not available.”However, if i is negative and no less than −n, then a useful convention is employed toreturn all but the ith value of the vector. For example, x [−1] is all of x but the first entry.

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

Saved successfully!

Ooh no, something went wrong!