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.

Multivariate data 119mtcars[[’mpg’]] Alternate list access.Note, mtcars [’mpg’] is not avector but a dataframe.To access the value “30.4”mtcars[’Honda’,’mpg’]By name (with match)mtcars[19,1]By row and columnnumbermtcars$mpg[19]mtcars$mpg is avector, this is the 19th entry.output indicates that this isn’t the case. In the data-frame case, this list is then coercedinto a data frame. The vector notation specifies the desired variables.Table 4.4 summarizes the various ways to access elements of a data frame.4.2.3 Setting values in a data frame or listWe’ve seen that we can’t change a data frame’s values by attaching it and then assigningto the variables, as this modifies the copy. Rather, we must assign val¬ ues to the dataframe directly. Setting values in a data frame or list is similar to setting them in a datavector. The basic expressions have <strong>for</strong>ms likedf[rows, cols]=values1st$name=value, or1st$name[i]=value.In the [,] notation, if values does not have the same size and type as the values that we arereplacing, recycling will be done; if the length of values is too big, however, an errormessage is thrown. New rows and columns can be created by assigning to the desiredindices. Keep in mind that the resulting data frame cannot have any empty columns(holes).> df = data.frame(a=1:2,b=3:4) # with names> df[1,1]=5 # first row, firstcolumn> df[,2]=9:10 # all rows, secondcolumn> df[1:2,3:4] = cbind(11:12,13:14) # rows and columnsat once> df # new columns addeda b c d1 5 9 11 132 2 10 12 14> df[1:2, 10:11]=cbind(11:12,13:14) # would create aholeError in "[

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

Saved successfully!

Ooh no, something went wrong!