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 120a b c d1 5 0 0 132 2 0 0 14<strong>Using</strong> $ with a list refers to a data vector that can be set accordingly, either all at once orposition by position, as with:> 1st = list(a=1:2,b=l:4,c=c("A","B","C"))> lst$a = 1:5 # replace the datavector> lst$b[3] = 16 # replace singleelement> lst$c[4]= “D" # appends to thevector> 1st$a[1] 1 2 3 4 5$b[1] 1 2 16 4$c[1] "A" "B" "C" "D"The c() function can be used to combine lists using the top-level components. This can beused with data frames with the same number of rows, but the result is a list, not a dataframe. It can be turned into a data frame again by using data.frame().4.2.4 Applying functions to a data frame or listIn Chapter 3 we noted that apply() could be used to apply a function to the rows orcolumns of a matrix. The same can be done <strong>for</strong> a data frame, as it is matrix-like.Although many functions in R adapt themselves to do what we would want, there aretimes when ambiguities <strong>for</strong>ce us to work a little harder by using this technique. Forexample, if a data frame contains just numbers, the function mean() will find the mean ofeach variable, whereas median() will find the median of the entire data set. We illustrateon the ewr (<strong>Using</strong>R) data set:> df = ewr[ , 3:10] # make a data frame ofthe times> mean(df) # mean is as desiredAA CO DL HP NW TW UA US17.83 20.02 16.63 19.60 15.80 16.28 17.69 15.49> median(df) # median is not asdesiredError in median(df) : need numeric data> apply(df,2,median) # median of columnsAA CO DL HP NW TW UA US16.05 18.15 15.50 18.95 14.55 15.65 16.45 14.45

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

Saved successfully!

Ooh no, something went wrong!