Skip to Main Content

Learn R

This guide focuses on transformation and cleaning functions in R that are especially useful for working with tabular datasets.

Functions for Viewing Data

str(df)  #shows the internal structure of the data frame











head(df)  # tells you the first six lines of a vector, matrix, table, data frame, or function

Other Functions

tail(df) # tells you the last six lines of a vector, matrix, table, data frame, or function
summary(df) # shows the statistical summary
ls() # lists all of the objects available in the workspace, i.e., all the data and variables you have defined
ls.str() # combines ls and str to lists all objects with details about data type and content
class() # tells you the data type, i.e., vector, matrix, character, etc.
names() # can either change the name of an object or tells you all of the defined names in the object
object.size() # tells you how much memory is taken up on your computer by the object
dim() # tells you the dimensions of the object
length() # tells you the length (number) of the vectors and factors in the object
ncol() # tells you the number of columns
nrow() # tells you the number of rows

Accessing Columns in a Data Frame

Let’s say we want to find the mean of the input column “TOTINC” in R. We do that as shown below:

Hence, to access TOTINC, we need to use df$TOTINC. However, to access the columns directly in R, you can use the function attach, after which you can refer to the columns directly as shown below:

You can and should use detach(df) to detach the data frame once you don’t need to directly access the variables.

Note: When working with multiple data frames, DO NOT use attach as it might cause a lot of confusion, rather use WITH() function, the details of which are beyond the scope of this document.

Liaison Librarian

Profile Photo
Martin Morris
Schulich Library of Physical Sciences, Life Sciences and Engineering
Macdonald-Stewart Library Building
809 rue Sherbrooke Ouest
Montréal, Québec H3A 0C1
(514) 398 8140
Website Skype Contact: martinatmcgill
Social: Twitter Page

McGill LibraryQuestions? Ask us!
Privacy notice