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 113Accessing a data frame using [,] notationWhen we use a spreadsheet, we refer to the cell entries by their column names and rowsnumber. Data-frame entries can be referred to by their column names (or numbers) and/ortheir row names (or numbers).Entries of a data vector are accessed with the [] notation. This allows us to specify theentries we want by their indices or names. If df is the data frame, the basic notation isdf[row, column]There are two positions to put values, though we may leave them blank on purpose. Inparticular, the value of row can be a single number (to access that row), a vector ofnumbers (to access those rows), a single name or vector of names (to match the rownames), a logical vector of the appropriate length, or left blank to match all the rows.Similarly <strong>for</strong> the value of column. As with data vectors, rows and columns beginnumbering at 1.In this example, we create a simple data frame with two variables, each with threeentries, and then we add row names. Afterward, we illustrate several styles of access.> df=data.frame(x=1:3,y=4:6) # add in column names> rownames(df)=c("row 1","row 2","row 3") # add rownames> dfx yrow 1 1 4row 2 2 5row 3 3 6> df[3,2] # row=3,col=2[1] 6> df["row 3","y"] # by name[1] 6> df[1:3,1] # rows 1, 2 and 3;column 1[1] 1 2 3> df[1:2,1:2] # rows 1 and 2, columns1 and 2x yrow 1 1 4row 2 2 5> df[,1] # all rows, column 1,returns vector[1] 123> df [1,] # row 1, all columnsx yrow 1 1 4> df[c(T,F,T),] # rows 1 and 3 (T=TRUE)x yrow 1 1 4row 3 3 6■ Example 4.4: <strong>Using</strong> data-frame notation to simplify tasks

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

Saved successfully!

Ooh no, something went wrong!