10 - 8[1] 2
23 * 2[1] 46
5 / 5[1] 1
log(90)[1] 4.49981
Getting Started with R
Tue. Sep 29, 2026 – 6:00 pm
After attending this training session, you will be able to:
For this training session, please download the following data:
R is statistical software that is licensed as an open source program under a GNU license. In other words, it is free to download, free to modify, and free to share with other people. It can be used for data manipulation, calculation, inference, and graphical display. It contains advanced statistical procedures sometimes not available in other statistical software. It is available on Windows, Linux, and Mac, and can be downloaded for free at https://cran.r-project.org/.
RStudio is a user interface for using the R statistical programing language. We highly recommend using RStudio (or another program like Positron, but we will only cover RStudio today). RStudio can be downloaded from the Posit website https://posit.co/products/open-source/rstudio/.
To use RStudio, you must first install R on your computer.
The GSS is a demographic and opinion survey of U.S. households conducted by the National Opinion Research Center (NORC) at the University of Chicago. It has been collected annually or biannually (depending on the availability of funding) since 1972.
More than 38,000 respondents have answered over 3,000 different questions with regard to their opinions and attitudes toward economic, social, and political issues. It is well known for having the highest quality in overall survey design and is often used for examples in introductory statistics textbooks.
A subset of the 2018 GSS is used in this tutorial.
To launch RStudio, click on the start icon
in the lower left-hand corner of the screen. Select RStudio from the list of programs.
The RStudio interface consists of four panes by default: the Script Editor, the Console, the Workspace pane, and the Viewer.
The Menu Bar has pull-down menus that display additional commands when clicked.
The R Console window can be used to enter commands and view printed results or messages (errors, warnings, information, etc.).
R has a built-in command-line calculator, which is useful for quick math expressions and data transformations that you don’t want to save in a script.
Go to the R Console and type a basic mathematical expression, such as 10 - 8, 23 * 2, 5 / 5 or log(90).
After each expression, press ENTER.
The results should appear as below:
You can use the up or down arrow keys (↑ and ↓) on the keyboard to cycle through previously entered commands and re-run them.
Scripts (and their cousins, R Markdown and Quarto documents) are the basic units of R programming. They are text files with a .R (or .Rmd/.qmd) file extension that contain a series of R expressions, which can be executed in the R Console.
In an R session, you cannot save commands written in the console, so you will do most of your work in the Script Editor, where you can save your work for later use. Writing your scripts so that the code is readable and can run from top to bottom without errors will let you share your work with others and reproduce your results later.
To create a new script in RStudio, click on the New File button in the upper left hand corner of RStudio or use the keyboard shortcut Ctrl + Shift + N (Cmd + Shift + N on Mac). Then click on R Script to create a new empty R Script.
In R, any lines beginning with # are treated as comments. Commented lines are useful for adding descriptive information to your code. R will not run any code in a line after a pound sign. For example:
To execute a command written in the Script Editor, place the cursor on the line containing the command, and then type Ctrl + Enter (Cmd + Enter on Mac). The executed command will also appear in the R Console.
To run multiple commands at once, highlight the desired lines in the Script Editor and type Ctrl + Enter (Cmd + Enter on Mac).
To save the script, click File > Save as… or press Ctrl + S (Mac: Cmd + S).
The Workspace consists of all of the objects defined by the user.
In RStudio, a summary of the objects in memory will be displayed in the Environment tab of the Workspace pane. This may consist of data frames, lists, vectors, or other objects.
Data frames and lists can be previewed in the Environment tab by clicking on the triangle next to the object name. This will display information about the variables in the data frame, such as name, object type (numeric, factor, etc.), and the first values. The number of variables and observations are also listed next to the name of the data frame.
If you want to remove objects from your workspace environment, you can do so using the code remove(list="my.data"), where my.data is the name of the object you want to delete. You can also remove all objects at once by restarting your R session (Session > Restart R or Ctrl + Shift + F10).
Also, note that in RStudio, data can be loaded by clicking on Import Dataset in the Environment tab of the Workspace pane. Code for loading the data set is recorded in the Console and History.
In the History tab of the History/Environment pane, a list of all the commands entered are displayed. Double clicking on a previous command automatically sends the command to the console.
In the Viewer pane, you will be able to search for files, display information about R packages, and explore help pages. Some outputs from the Console, such as graphs, plots, and help requests, will be displayed here as well.
To become familiar with how the Console and the Viewer pane interact, let’s open the documentation for the plot() function:
Remember to press Enter to execute a typed command. (You use Ctrl + Enter when working in the Script Editor, but you would generally use the Console, not the Script Editor, to open documentation because reading the documentation is an as-needed event, not a regular part of your data analysis workflow). Information about the plot function should be displayed in the Viewer.
Now let’s display something in the Plot tab of the Viewer pane.
In the script editor (or in the console), enter:
You will see the plots in the lower right hand pane, with the Plot tab activated.
If you click on the Help tab, you will see the last help topic.
There are a few tips to keep in mind when using the Console:
Plot() or PLOT() instead of plot(), you will get an error message stating that R could not find that function.>) is the R prompt that means the console is ready for your input. If you do not complete a command, for example by omitting a closing parenthesis, you will instead see a + at the beginning of the next line. To complete the command, just add the remaining element of the command directly after the + sign. Or, delete the incomplete command and try again.;). Example: print("hi"); print("bye")') or double quotation marks (") for specifying text, but be consistent within a command. If you want to enter text that contains an apostrophe, use double quotation marks to enclose the text. For example, print("It's a nice day") will work, but print('It's a nice day') will not.install.packages(spdep) instead of install.packages("spdep") will return an error. Check the syntax for the function you are using.Data/raw/myfile.csv instead of Data\raw\myfile.csv (even though Windows normally uses backslashes for file paths).\n at the end of the line, which means “new line”, e.g., cat("This is the first line.\nThis is the second line.")A package is a collection of functions, data, and documentation bundled together.
R comes equipped with a standard set of packages that contain basic functions and a few datasets (called “base R”). However, one of the main strengths of R is the ability to add additional packages that contain functions and datasets for specific purposes. Since R is open source, anyone can write a package, and you can easily download and use other people’s packages. The R community is constantly developing and improving packages, and if you need a function that doesn’t currently exist, you can write it yourself, or you can ask the author of an existing package to add what you need.
R packages make it possible to do advanced statistical analyses, easily create graphics, scrape data from websites, create dashboards, and much more.
You will need to be connected to the internet to install packages. To install a package, you can either:
install.packages("packagename")Try installing the package dplyr using install.packages("dplyr").
Packages are installed to a “library,” which is a folder on your computer that R can access. You can check which packages are installed on your computer by typing library() in the R Console or by looking under the Packages tab of the Viewer pane.
Once packages are installed, they need to be loaded from the library into your R session. You can load a package by typing library(packageName) (e.g. library(dplyr)). Note that each time you start a new R session, you will need to load the packages you want to use.
You can also access functions from a package by using the syntax packageName::functionName (e.g., dplyr::filter()), which allows you to use a function from a package without loading the entire package. This is useful if you know you only need one or two functions from a package, or if you have multiple functions with the same name from different packages.
You generally only need to install packages once on a computer, or once after you update to a new version of R.
Do not put install.packages() code in your scripts – there is no need to reinstall packages every time you run your code. Instead, just load the package with library(packagename).
Best practice: Put all your library() calls at the top of your R script so that you can see all the packages you are using in one place.
Once a package is loaded, more information about the package can be obtained by typing help(package=packageName) or by searching for or locating the package under the Packages tab of the Viewer pane. Continuing with our dplyr package example, type help(package=dplyr). This will open the documentation for the dplyr package in the Help tab of the Viewer pane.
help(functionName), or ?functionName.help(functionName, package="packageName") or ?packageName::functionName.?? operator to broaden your search to include all installed packages. For example, use ??filter will search for the function filter in all installed packages.Entering help(filter) will open a new page in the Help tab of the Viewer pane showing the R documentation for the filter function in the dplyr package. The function library() will display all R packages installed.
If you plan to read or write data files or other objects, you will need to set R’s working directory. Setting a working directory means you can use relative paths when you import or export files, which is more flexible than using absolute directories.
When you open RStudio, it will open a standard working directory unless you open an RStudio Project (in which case, it will open directly to the project’s directory). To see which directory is active in the current session, enter the function getwd().
To change the working directory, you can either a) set it via code or b) use the Session menu. To change via code, use the setwd() function with the desired destination. Note: Do not include setwd() in scripts you share or reproduce; it will cause errors, because other people’s computers do not have the same file paths as your computer.
After typing and entering setwd("C:/Users/YourNetId/Desktop/RI"), the current working directory is changed to "C:/Users/YourNetId/Desktop/RI". (Replace YourNetId with your actual NetID.) You can check that the working directory has been changed by entering getwd() again.
To change via the menu, go to Session > Set Working Directory and Choose Directory… if you want to choose a certain directory or have not saved your script file; choose To Source File Location if you have already saved your script on your computer.
Best practice: Avoid writing setwd() inside scripts, because it can make your code less portable and harder to share.
Instead, we recommend using RStudio Projects to manage working directories automatically. See David Chen’s post Why use Projects for details.
The list.files() function returns a character vector of the names of files or directories in the current directory. When you put a path in the parameter, a character vector of the names for the specified directory will be displayed.
The c() function concatenates (combines) values into a vector.
Usage: P <- c(X,Y,Z, ...)
The matrix() function creates a matrix from a given set of values.
Usage: mat <- matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
Data frames are similar to matrices, but different columns can have different data types (numeric, character, etc.).
Data frames are used as the fundamental data structure by most of R’s modeling software.
Usage: mydata <- data.frame(X,Y,Z...)
A list is a container, similar to a vector but it can hold objects of different types and sizes. (You can think of it like a junk drawer – lists can contain almost anything, including other lists.)
Usage: myList <- list(name=" ", X, Y, Z...)
Factors are used to encode a numeric vector into a categorical or ordinal variable.
Usage: myFactor <- factor(data)
The output displays the factor values.
The Data Editor window displays a table.
The read.csv() function reads a .csv file and sets it as the data object.
Example:
"R_Data.csv") instead of specifying the full (absolute) path to the file (e.g., "C:/Users/YourNetId/Documents/R_Data.csv").header=TRUE specifies that the first row of the file is a header with column names. If the first row does not contain column names, you would use header = FALSE instead.na.strings=c("", "NA") tells the function that both empty strings ("") and the string NA should be treated as missing (NA).stringsAsFactors specifies whether character strings should be converted to factors (i.e., categorical variables for use in statistical modeling). In older versions of R (prior to R 4.0), the default was TRUE, which could cause problems if you didn’t know that your character strings would be converted, but in newer versions, the default is FALSE. In this example, we set it to FALSE in case anyone is using an older R version. After the data is imported, we can manually convert some or all of the character strings to factors.read_csv() function from the readr package, which is part of the tidyverse collection of packages. It has similar arguments to read.csv(), but it is faster and more flexible.Now let’s load the training dataset the same way, using the R_Data.csv file you downloaded above (and placed in your working directory):
Similarly, read.table() can be used to import .txt files. The arguments for this function are very similar to read.csv() except that header is FALSE by default (it is TRUE by default in read.csv).
Several packages make importing Excel files very easy in R. The two most popular packages are readxl and xlsx. The functions in these packages have similar arguments to other base import functions. Excel import functions will let you specify which sheet to import as well as specific data ranges if your file contains multiple sheets or if the data is not in a contiguous block.
R can import data from SPSS, SAS, and STATA formats using similar methods. You can use the haven or rio packages to import those formats. For example:
This section explains some frequently used functions to view or grab information about the data.
dataObject$variableName: Returns the vector defined by the variableName contained in dataObject. This can be used to specify a variable for use in other functions.
Example:
[1] 14 10 16 16 18 16 13 12 8 12 19 14 13 16 12 12 16 16 20 18 15 14 14 12
[25] 16 8 12 9 12 14 12 8 16 16 10 18 20 20 19 12 12 12 12 18 16 12 18 18
[49] 17 16 14 12 18 18 16 14 16 14 11 9 13 10 16 13 12 20 14 14 19 16 15 16
[73] 16 20 14 14 16 8 14 NA 16 12 12 13 12 17 13 16 18 18 16 19 16 12 16 14
[97] 13 16 12 4 12 12 18 14 18 14 12 12 16 14 14 12 14 12 16 17 8 14 13 13
[121] 12 12 16 16 16 18 20 16 18 18 12 20 17 15 13 12 16 16 12 15 14 17 11 12
[145] 12 12 12 17 14 19 16 13 12 16 8 11 12 14 7 2 11 12 12 15 6 13 9 16
[169] 18 13 12 14 13 16 20 16 18 14 16 14 12 16 20 17 16 14 11 16 14 13 12 18
[193] 6 16 11 16 12 12 16 14 16 13 16 13 16 12 12 12 16 12 14 14 10 11 12 15
[217] 7 3 12 12 19 16 12 14 16 15 11 17 12 12 15 16 17 12 12 17 10 12 18 13
[241] 14 13 13 13 14 12 12 13 16 12 12 16 14 12 10 1 12 16 16 12 16 16 16 16
[265] 16 13 16 14 16 12 12 18 14 19 16 16 18 15 12 16 12 13 14 12 16 12 18 15
[289] 12 12 17 19 12 12 11 16 11 20 20 16 16 13 12 20 14 12 17 8 12 16 14 16
[313] 18 20 13 16 19 12 20 12 14 12 11 7 12 10 12 14 17 16 14 16 19 12 18 12
[337] 16 16 16 16 20 16 16 18 14 13 12 12 12 15 14 12 20 16 20 12 9 18 14 12
[361] 12 13 14 16 17 6 16 16 18 16 16 16 16 15 16 14 14 14 16 16 12 12 19 15
[385] 16 16 16 20 14 14 13 18 9 17 0 16 12 19 12 16 16 12 12 3 12 15 11 14
[409] 13 13 15 10 14 15 8 16 13 12 14 16 13 14 12 13 12 20 18 20 16 12 16 16
[433] 18 16 5 16 12 16 18 14 18 16 17 12 12 12 16 16 12 0 12 17 12 16 18 13
[457] 19 16 12 14 16 17 15 16 16 14 14 15 16 14 18 19 16 18 9 15 18 20 12 13
[481] 18 15 12 12 16 11 16 12 12 14 16 16 20 20 17 11 13 6 10 16 12 16 16 11
[505] 16 14 17 16 17 16 18 16 16 17 16 14 16 18 16 12 18 12 12 14 13 12 12 13
[529] 12 12 12 13 12 18 14 14 2 18 13 12 17 16 16 13 17 12 12 11 12 20 16 13
[553] 16 12 17 14 16 16 17 16 17 12 16 16 16 16 16 20 16 16 20 16 20 12 14 12
[577] 16 14 15 12 20 12 12 12 12 7 17 15 18 14 11 16 13 12 16 14 12 16 19 12
[601] 11 14 13 12 16 12 9 14 9 11 5 9 10 15 9 7 14 12 16 12 16 12 20 14
[625] 19 15 19 20 16 17 16 12 15 15 18 12 12 12 13 12 16 14 15 11 14 18 14 11
[649] 6 3 9 12 19 16 12 16 12 14 13 14 13 13 12 15 16 16 14 17 13 12 16 12
[673] 12 15 14 14 14 13 12 15 15 15 16 3 12 12 12 11 12 12 12 14 15 12 12 12
[697] 4 12 16 4 13 13 12 9 14 12 12 12 15 12 9 16 18 12 11 18 13 18 18 18
[721] 11 16 15 16 12 15 13 14 12 12 14 13 18 10 16 14 16 12 14 17 12 16 10 12
[745] 12 14 16 12 12 13 12 15 10 12 18 11 20 16 18 14 16 16 16 16 15 18 17 9
[769] 12 16 19 16 12 14 14 14 14 8 16 12 16 14 13 17 12 15 12 8 12 14 12 16
[793] 12 NA 20 15 12 15 14 15 3 12 12 16 7 12 16 12 16 13 16 18 16 15 12 12
[817] 12 12 12 12 18 16 15 12 14 16 12 16 16 12 16 13 12 12 19 16 12 12 14 10
[841] 9 14 12 15 14 12 12 14 14 14 16 12 6 17 14 14 16 16 17 12 16 16 13 16
[865] 12 12 15 13 20 15 8 12 16 16 12 16 16 16 12 17 17 16 14 16 16 12 18 12
[889] 14 16 12 16 12 15 12 13 16 12 12 12 11 12 12 12 13 13 12 12 14 20 12 14
[913] 15 14 10 14 11 14 14 12 20 12 12 16 16 12 17 12 20 14 18 18 19 16 14 16
[937] 17 18 13 12 14 11 15 11 12 17 18 15 12 14 9 17 14 9 12 18 6 9 12 6
[961] 14 16 16 16 13 14 14 14 12 11 16 13 12 14 12 16 16 13 18 18 17 16 18 13
[985] 16 20 17 16 13 13 12 14 16 13 12 15 14 15 13 12 16 15 16 16 20 20 16 16
[1009] 16 18 14 13 16 16 16 14 13 14 13 18 13 12 12 10 16 14 12 16 12 16 12 14
[1033] 15 16 15 10 12 16 12 18 16 14 20 14 17 14 12 18 11 6 10 12 12 13 12 13
[1057] 9 12 13 13 12 11 14 12 12 15 11 15 13 14 13 11 16 13 14 16 15 16 8 14
[1081] 12 13 9 13 9 16 9 16 14 16 16 18 16 16 12 17 14 17 13 13 9 13 12 12
[1105] 11 12 13 17 18 16 12 18 12 15 12 18 15 12 12 12 15 12 16 16 15 16 15 15
[1129] 17 16 13 14 15 16 20 12 8 12 12 20 16 14 12 14 19 16 12 12 11 17 9 13
[1153] 17 12 13 16 14 14 12 16 11 12 13 20 16 16 16 12 12 16 16 12 12 18 16 12
[1177] 13 12 12 12 13 13 12 10 16 16 17 12 12 16 14 12 14 11 18 12 16 12 17 11
[1201] 12 16 16 16 14 18 14 12 12 12 13 15 12 16 11 13 14 12 12 16 16 12 11 8
[1225] 14 20 11 13 10 15 12 12 14 16 17 16 14 15 15 12 17 18 16 18 12 11 13 12
[1249] 9 12 13 12 16 12 13 12 12 12 12 16 16 14 16 16 16 16 15 5 14 17 14 10
[1273] 15 12 16 11 3 20 16 12 16 16 16 11 12 9 18 17 14 15 20 12 14 12 11 9
[1297] 14 12 11 12 16 15 14 16 12 18 12 12 16 12 13 8 12 14 14 16 12 16 12 16
[1321] 12 12 13 12 14 10 12 12 12 12 12 17 12 14 18 3 16 16 12 3 10 6 14 12
[1345] 13 13 14 10 18 13 13 15 15 12 12 20 14 16 18 14 14 15 12 12 12 10 12 16
[1369] 12 14 12 14 18 12 16 14 16 15 13 16 3 14 14 19 18 16 8 14 20 16 15 18
[1393] 11 12 12 19 9 13 12 16 12 11 13 16 15 18 12 14 10 13 12 10 13 12 15 15
[1417] 14 10 11 14 14 14 11 18 16 15 16 10 14 16 14 14 16 15 14 17 15 17 12 16
[1441] 12 14 16 16 16 18 16 10 10 12 12 12 13 18 8 12 11 13 16 18 15 12 13 12
[1465] 12 16 20 15 13 13 17 9 14 11 8 14 12 16 16 12 12 14 16 16 16 14 12 16
[1489] 18 17 16 18 16 13 12 14 12 14 18 13 12 12 14 16 6 14 13 6 17 13 16 14
[1513] 12 14 8 13 14 15 14 12 12 10 12 11 0 12 10 12 11 13 13 12 15 10 9 15
[1537] 13 9 12 10 19 12 20 11 17 12 12 11 13 16 14 12 11 14 16 17 10 17 12 14
[1561] 18 14 18 19 14 11 16 12 15 17 10 15 12 12 18 14 11 14 12 15 12 14 12 14
[1585] 14 12 13 13 14 16 16 12 11 16 16 14 11 12 9 12 20 14 16 16 12 17 13 14
[1609] 14 12 12 13 12 12 14 12 12 14 16 17 16 19 16 16 15 15 12 12 12 8 12 12
[1633] 12 12 12 14 19 17 13 11 11 16 16 15 14 12 15 12 12 14 14 13 14 14 16 12
[1657] 12 19 12 8 12 12 13 16 19 12 13 10 16 16 12 14 16 19 19 16 12 17 16 15
[1681] 16 17 15 12 12 20 12 12 12 18 16 15 16 18 9 12 11 12 13 13 13 16 12 12
[1705] 12 18 16 15 19 17 13 12 14 18 17 14 15 17 12 14 12 12 15 16 13 18 12 10
[1729] 14 16 17 18 12 12 14 12 12 16 17 12 11 16 11 18 16 12 11 10 10 12 12 16
[1753] 16 12 12 16 12 17 20 12 16 14 16 14 13 13 12 12 12 13 12 17 12 8 1 14
[1777] 14 12 20 13 16 12 12 14 16 15 16 16 16 16 20 12 12 13 13 16 18 16 16 11
[1801] 14 13 16 16 16 17 16 12 16 19 14 16 14 16 12 12 12 14 14 13 14 17 14 12
[1825] 12 12 16 11 16 12 13 16 12 11 12 12 14 12 14 16 12 16 13 12 19 15 15 12
[1849] 12 7 12 12 12 10 18 13 10 16 12 18 9 14 18 11 11 14 9 11 19 13 13 16
[1873] 11 13 12 6 12 10 12 9 13 8 12 12 9 12 12 12 12 12 11 10 11 8 13 10
[1897] 14 14 8 12 11 12 10 10 4 15 14 12 17 15 16 20 14 12 11 20 13 12 12 12
[1921] 14 12 16 15 11 17 13 12 12 16 11 20 9 20 12 16 18 16 19 16 20 12 16 14
[1945] 20 16 15 16 14 16 15 16 14 12 12 12 17 14 12 10 14 12 20 6 12 13 6 13
[1969] 14 16 14 16 16 13 9 12 15 16 2 9 12 13 18 16 12 13 12 12 12 12 11 0
[1993] 12 9 8 14 14 16 19 12 11 15 17 17 15 15 20 16 12 12 12 16 16 15 13 12
[2017] 12 15 18 15 14 15 18 17 20 16 20 19 14 19 15 16 14 14 14 12 14 9 10 12
[2041] 19 20 12 14 11 16 18 12 12 12 12 12 14 12 8 12 14 11 12 12 14 14 12 18
[2065] 14 12 9 10 14 15 11 11 9 12 12 12 18 12 12 12 14 14 14 16 12 12 12 14
[2089] 8 12 13 16 17 14 16 12 12 14 13 16 17 15 12 12 13 14 16 12 16 13 14 12
[2113] 12 20 14 12 10 14 10 12 14 13 14 14 14 14 13 12 17 7 12 12 20 16 15 12
[2137] 12 16 9 12 12 12 12 16 12 14 12 12 11 6 8 14 14 14 12 17 12 12 13 12
[2161] 12 19 12 9 12 14 14 9 10 16 12 12 12 12 12 12 12 14 12 12 12 12 12 16
[2185] 12 12 12 12 12 16 12 16 19 15 12 12 14 16 18 14 10 14 12 13 15 12 20 12
[2209] 16 14 20 14 8 12 12 12 17 12 13 12 12 19 2 13 18 16 12 11 13 12 17 14
[2233] 17 9 11 10 13 8 12 12 10 12 12 12 12 12 12 12 14 14 12 19 12 12 12 12
[2257] 12 8 10 3 16 16 6 13 14 4 12 12 12 12 8 11 14 10 15 14 14 13 17 12
[2281] 12 12 11 12 9 12 6 10 11 11 11 10 12 9 13 12 10 13 6 12 10 12 12 6
[2305] 10 12 12 12 9 14 13 14 8 12 12 NA 17 20 12 10 12 15 14 16 12 16 12 16
[2329] 17 14 14 12 17 20 18 18 16 12 12 14 8 14 12 12 12 12 16 12
names(dataObject): Displays the names of variables contained in the dataObject. Recall that we previously defined gssdata as our data object that refers to the actual data that we are pulling up with the read.csv function. Let’s list variable names in the data:
[1] "id" "age" "year" "wrkstat" "hrs1" "marital"
[7] "degree" "sphrs1" "postlife" "sex" "SIBS" "agekdbrn"
[13] "othlang" "born" "neisafe" "hsbio" "hschem" "natspac"
[19] "nextgen" "grass" "hrlax" "colsci" "fmi" "numpets"
[25] "trust" "tvhours" "sop" "ssi" "sphrs2" "educ"
[31] "moos" "faos" "realrinc" "wordsum" "rhs" "Male"
[37] "pres"
str(dataObject): Compactly displays the data structure of the dataObject. Using our gssdata as an example, we can see the number of variables, the number of observations, and the data type of each variable.
'data.frame': 2348 obs. of 37 variables:
$ id : int 1 2 3 4 5 6 7 8 9 10 ...
$ age : int 43 74 42 63 71 67 59 43 62 55 ...
$ year : int 2018 2018 2018 2018 2018 2018 2018 2018 2018 2018 ...
$ wrkstat : chr "temp not working" "retired" "working fulltime" "working fulltime" ...
$ hrs1 : int NA NA 40 40 NA NA 35 89 40 40 ...
$ marital : chr "never married" "separated" "married" "married" ...
$ degree : chr "junior college" "high school" "bachelor" "bachelor" ...
$ sphrs1 : int NA NA 40 40 NA NA NA NA NA NA ...
$ postlife: chr "yes" "yes" "yes" "yes" ...
$ sex : chr "male" "female" "male" "female" ...
$ SIBS : int 4 4 2 3 3 1 7 2 4 2 ...
$ agekdbrn: int NA 21 35 32 NA 27 18 NA 17 30 ...
$ othlang : chr "yes" "no" "no" "no" ...
$ born : chr "yes" "yes" "yes" "yes" ...
$ neisafe : chr "very safe" "very safe" "very safe" "very safe" ...
$ hsbio : chr "yes" NA "yes" NA ...
$ hschem : chr "yes" NA "yes" NA ...
$ natspac : chr "too much" NA "too little" NA ...
$ nextgen : chr "strongly agree" "strongly disagree" "agree" "strongly disagree" ...
$ grass : chr NA "not legal" "legal" "not legal" ...
$ hrlax : int 3 NA 3 7 NA NA 1 1 0 4 ...
$ colsci : chr "no" NA "yes" NA ...
$ fmi : int NA 14755 72640 119879 119879 NA 8512 24970 2497 45400 ...
$ numpets : int NA 0 NA 0 1 NA 1 0 NA 1 ...
$ trust : chr NA "can trust" "can't be too careful" "can trust" ...
$ tvhours : int 3 NA 1 1 NA 10 NA NA 4 2 ...
$ sop : int NA NA 45 59 NA NA NA NA NA 28 ...
$ ssi : int NA NA 44 69 NA NA NA NA NA 21 ...
$ sphrs2 : int NA NA NA NA NA NA NA NA NA NA ...
$ educ : int 14 10 16 16 18 16 13 12 8 12 ...
$ moos : int 31 32 32 NA 35 33 44 25 38 72 ...
$ faos : int 45 39 72 39 45 45 NA NA 45 44 ...
$ realrinc: int NA NA 45400 54480 NA NA 8512 17025 908 45400 ...
$ wordsum : int 9 NA 6 9 NA 9 NA NA 6 6 ...
$ rhs : chr NA NA NA NA ...
$ Male : chr "male" "female" "male" "female" ...
$ pres : int 47 22 61 59 53 53 48 35 35 39 ...
This dataset contains 37 variables (which matches the output from names(gssdata)). Most variables are numeric, factors (i.e., categorical), or character strings (i.e., text that does not represent categories).
View(dataObject) Opens dataObject in the Data Viewer pane. You can also open the Data Viewer by clicking the name of the object in the Environment tab of the Workspace pane.
fix(dataObject): Lets you manually edit dataObject. Note that manually editing data this way is generally not recommended, as it is easy to make mistakes or to lose track of what steps you have taken. It is better to use R functions to manipulate data, which leaves a clear trail that future-you can follow to understand your edits.
Changes you make in the Data Editor will apply immediately to your dataObject, but they will not automatically be saved to a file. To save those changes, use write.csv() or a similar function.
attach(dataObject)/ detach(dataObject): Attaches/Detaches a set of R objects to a search path. When a dataObject is attached, the variables in that object can be accessed by giving their names (e.g., you can type educ instead of gssdata$educ). If you are working with multiple data objects at once, it is best to avoid using attach() and detach() to prevent confusion about which object a variable belongs to. Instead, use the $ operator to specify the data object.
dim(object) – Displays dimensions of an object.
head(object) – Get the first several lines of an object.
id age year wrkstat hrs1 marital degree sphrs1
1 1 43 2018 temp not working NA never married junior college NA
2 2 74 2018 retired NA separated high school NA
3 3 42 2018 working fulltime 40 married bachelor 40
4 4 63 2018 working fulltime 40 married bachelor 40
5 5 71 2018 retired NA divorced graduate NA
6 6 67 2018 retired NA widowed bachelor NA
postlife sex SIBS agekdbrn othlang born neisafe hsbio hschem natspac
1 yes male 4 NA yes yes very safe yes yes too much
2 yes female 4 21 no yes very safe <NA> <NA> <NA>
3 yes male 2 35 no yes very safe yes yes too little
4 yes female 3 32 no yes very safe <NA> <NA> <NA>
5 yes male 3 NA no yes very safe <NA> <NA> <NA>
6 yes female 1 27 no yes very safe yes yes <NA>
nextgen grass hrlax colsci fmi numpets trust
1 strongly agree <NA> 3 no NA NA <NA>
2 strongly disagree not legal NA <NA> 14755 0 can trust
3 agree legal 3 yes 72640 NA can't be too careful
4 strongly disagree not legal 7 <NA> 119879 0 can trust
5 strongly disagree not legal NA <NA> 119879 1 can trust
6 strongly agree <NA> NA yes NA NA <NA>
tvhours sop ssi sphrs2 educ moos faos realrinc wordsum rhs Male pres
1 3 NA NA NA 14 31 45 NA 9 <NA> male 47
2 NA NA NA NA 10 32 39 NA NA <NA> female 22
3 1 45 44 NA 16 32 72 45400 6 <NA> male 61
4 1 59 69 NA 16 NA 39 54480 9 <NA> female 59
5 NA NA NA NA 18 35 45 NA NA <NA> male 53
6 10 NA NA NA 16 33 45 NA 9 <NA> female 53
tail(object) – Get the last several lines of an object.
id age year wrkstat hrs1 marital degree sphrs1
2343 2343 19 2018 school NA never married high school NA
2344 2344 37 2018 working fulltime 36 divorced high school NA
2345 2345 75 2018 working parttime 36 married high school NA
2346 2346 67 2018 retired NA married high school NA
2347 2347 72 2018 retired NA married high school 4
2348 2348 79 2018 keeping house NA widowed high school NA
postlife sex SIBS agekdbrn othlang born neisafe hsbio hschem
2343 no male 3 NA no yes somewhat safe <NA> <NA>
2344 yes female 9 29 no yes very safe no no
2345 yes female 9 19 no yes very safe no no
2346 <NA> female 3 22 no yes very safe <NA> <NA>
2347 yes male 1 31 no yes very safe yes yes
2348 yes female 10 21 no yes very safe no no
natspac nextgen grass hrlax colsci fmi numpets
2343 about right <NA> legal NA <NA> 7377 2
2344 too much agree <NA> 4 no NA NA
2345 too much strongly agree <NA> 5 no 14755 NA
2346 <NA> <NA> legal NA <NA> 45400 0
2347 about right disagree not legal NA yes 24970 NA
2348 <NA> strongly agree <NA> NA no NA NA
trust tvhours sop ssi sphrs2 educ moos faos realrinc
2343 can't be too careful NA NA NA NA 12 39 35 NA
2344 <NA> 2 NA NA NA 12 31 72 NA
2345 <NA> 6 35 32 NA 12 NA 27 7377
2346 can trust NA NA NA NA 12 45 53 1589
2347 can trust 1 64 84 NA 16 53 50 NA
2348 <NA> 1 NA NA NA 12 NA 46 NA
wordsum rhs Male pres
2343 NA excellent male NA
2344 5 <NA> female 47
2345 4 excellent female 28
2346 NA <NA> female 40
2347 5 good male 47
2348 2 <NA> female 33
While we can use base R to compute many descriptive statistics, there are many packages that provide additional functionality or may be simpler to use.
For example, you can get concise statistical description of the data using the describe function in the psych package. As explained above, you may need to install the psych package. After it is installed, load it using library(psych).
The describe() function provides a concise statistical summary for numeric variables. The statistical summary typically includes the number of observations, central tendency statistics (mean, median, sd), range, and skew and kurtosis. The following is the output for the variable age:
vars n mean sd median trimmed mad min max range skew kurtosis se
X1 1 2341 48.97 18.06 48 48.4 22.24 18 89 71 0.22 -0.91 0.37
Run frequencies for the variable SIBS (number of siblings).
Categorical (factor) variables can be summarized in R using frequency and proportion tables. The freq() function from the descr package prints a frequency table and displays a bar chart for the selected variable.
gssdata$sex
Frequency Percent
female 1296 55.2
male 1052 44.8
Total 2348 100.0
If there are missing values in the variable, freq() will count those and additionally display a Valid Percent that ignores NA values. You can also count NA values using sum(is.na()) (example below).
To create new variables based on existing variables, use the assignment operator <-. (You can also use =, but <- is the preferred operator in R.) Note that to create a new variable in a dataframe, you have to use the object name and $ notation to specify the name of the created variable. For instance, you need to type gssdata$sqrtage rather than sqrtage so that the system understands the newly created variable is an element of gssdata rather than a stand-alone variable.
[1] 43 74 42 63 71 67 59 43 62 55
[1] 6.557439 8.602325 6.480741 7.937254 8.426150 8.185353 7.681146 6.557439
[9] 7.874008 7.416198
Note that referring to sqrtage on its own (rather than gssdata$sqrtage) produces an error, since it is not a stand-alone variable in your environment:
The above codes create a new variable sqrtage by calculating the square root of the existing age variable.
Newly created variables are not included in any previous attach() calls. In this example, an error results since variable did not exist when we attached gssdata.
You can recode an existing variable into a new variable by changing, rearranging, or consolidating the values of the existing variable. Recoding allows you to:
income, age) into a categorical variable with few levels (for example, variable incomeRecode can have “low”, “medium”, and “high” as values, and ageRecode can have “young”, “adult”, and “senior” as values).In this workbook, we will focus on recoding using base R syntax. Other popular options for recoding include the recode() function in the car package and the mutate() function in the dplyr package.
To recode a variable, one or more of R’s logical operators are used. The following table lists R’s common logical operators.
| Operator | Description |
|---|---|
| == | Equal to |
| != | Not equal to |
| < | Less than |
| > | Greater than |
| <= | Less than or equal to |
| >= | Greater than or equal to |
| !x | Not x |
| x | y |
| x & y | x AND y |
| isTRUE(x) | Test if x is TRUE |
Note: x and y are expressions.
The basic syntax is: newVariable[ConditionOnExistingVariable] <- newValue
The newValue part of the syntax will only execute when the specified ConditionOnExistingVariable is TRUE.
For instance, you can transform a continuous variable, such as age, into a categorical variable. In this example, the new variable is called agecat and has three levels: “Young”, “Middle Aged”, and “Elder”.
[1] "Young" "Middle Aged" "Young" "Middle Aged" "Middle Aged"
[6] "Middle Aged" "Middle Aged" "Young" "Middle Aged" "Middle Aged"
[1] "character"
We can see this new variable in the Data Editor,
You may want your data to be structured as a factor variable rather than a character/string variable. This can be accomplished by declaring the data to be factors, and identifying the levels with the factor() function.
[1] Young Middle Aged Young Middle Aged Middle Aged Middle Aged
Levels: Young Middle Aged Elder
[1] "factor"
You will see that R shows the first six values of agecat2 and has recognized it as a factor. head() also shows the three levels in agecat2: “Young”, “Middle Aged”, and “Elder”. You can double how R recognizes agecat2 by using the str() or levels() functions.
Factor w/ 3 levels "Young","Middle Aged",..: 1 2 1 2 2 2 2 1 2 2 ...
[1] "Young" "Middle Aged" "Elder"
Lastly, to verify that the variable has been recoded correctly, simply run a frequency on both the original variable and the recoded variable using the table() function.
Here, in the recoded variable agecat, the elder group includes 185 people, the middle aged group includes 1079 people and the young group has 1077.
We can also use the subset() function to get all the people in the elder group and use dim() to count the number of people in this group. By repeating this procedure for the rest of the groups we see that there are 185 people classified as elder, 1079 people classified as middle-aged, and 1077 people classified as young. From this, we can conclude our recoding is correct.
[1] 185 40
[1] 1079 40
[1] 1077 40
Create new variables to represent the recodes of the variable hrs1 (number of hours worked in the last week) into less than 40 and more than 40 (two groups), and recode all missing values to NA. Be sure to check the new variables by creating a frequency table.
The table() function creates a contingency table. A contingency table is used to show the joint distribution of cases over two or more categorical variables. The basic syntax to produce a contingency table, mytab <- table(var1, var2), will result in a table with var1 in the rows and var2 in the columns. Let’s create a contingency table using the variables postlife and sex. In our dataset, postlife contains information telling us if the respondent believes in life after death, and sex is the gender of the respondent.
The crosstab() function from the descr package creates a crosstab, which allows you to compare two or more categorical variables. The crosstab function is easier to use and more sophisticated than the base R table() function. It allows for chi-squared tests and other more specialized outputs. In order to use this function, check if the descr package is installed (by looking at the Packages pane or running 'descr' %in% installed.packages()). If it is not, install it to your machine using install.packages("descr"). Then, load it into your R session with library(descr). Again, to learn about the functions within this library you can enter help(package=descr).
Now we will reproduce our contingency table comparing postlife and sex using the crosstab() function.
Cell Contents
|-------------------------|
| Count |
|-------------------------|
==================================
gssdata$postlife
gssdata$sex no yes Total
----------------------------------
female 161 1017 1178
----------------------------------
male 242 703 945
----------------------------------
Total 403 1720 2123
==================================
To get row, column, and/or total percentages, add prop.r=TRUE, prop.c=TRUE, and/or prop.t=TRUE to the function like so:
Cell Contents
|-------------------------|
| Count |
| Column Percent |
|-------------------------|
====================================
gssdata$postlife
gssdata$sex no yes Total
------------------------------------
female 161 1017 1178
40.0% 59.1%
------------------------------------
male 242 703 945
60.0% 40.9%
------------------------------------
Total 403 1720 2123
19% 81%
====================================
Find out how many foreign-born and native-born survey respondents can speak a language other than English. That is, run a crosstab using variables othlang (Can respondent speak a language other than English?) and born (Was respondent born in this country?).
A histogram visually displays the distribution of a continuous variable. In R, the hist() function works as shown below:
A bar graph can display the frequencies or distribution of a categorical variable. First, a data table must be created for plotting. In this case, we named our data table counts:
Create a bar chart for the variable neisafe.
This variable is based on the question, “How safe interviewer thinks neighborhood is”. The answers are categorized as: “very safe”, “somewhat safe”, “somewhat unsafe”, “very unsafe”. Include the title “Interviewer’s Perception of Neighborhood Safety”.
A grouped bar graph is a bar graph that uses an additional variable to group the plotted data.For example, create a grouped bar graph displaying sex and marital. First, a data table must be created for plotting. In this case, we named our data table counts:
Next, add the syntax for the bar plot, where main is the title for the graph, xlab is the x-axis label, and ylim is used to set the y-axis height, in this case 600.
To reorder the marital status categories, try the following syntax. Another great package for plotting is called ggplot2. ggplot2 is extremely customizable and produces beautiful plots. We will produce this plot using ggplot2 code:
divorced married never married separated widowed
403 998 670 75 200
Attaching package: 'ggplot2'
The following objects are masked from 'package:psych':
%+%, alpha
A scatterplot plots the “positions” of two variables in dimensions x and y. We run the plot() function:
Here’s the plot using ggplot2, filling the points and fitting linear regression lines by sex:
`geom_smooth()` using formula = 'y ~ x'
Warning: Removed 10 rows containing non-finite outside the scale range
(`stat_smooth()`).
Warning: Removed 10 rows containing missing values or values outside the scale range
(`geom_point()`).
Note: the warning message just displays how many missing values were removed from the plotted data.
In ggplot2, the + operator is used to add layers to the plot. The first layer usually contains the data and “aesthetics mappings” (i.e., which variable should be assigned as the x axis, the color, etc.), and the subsequent layers are the geometric objects (points, lines, etc.) and other modifications (labels, themes, etc.).
Output data can be exported to many different file formats. For example:
This statement exports the modified gssdata to a text file using “,” as the separator. If append = TRUE, the gssdata will be appended to the current file.
This statement exports the modified gssdata to a csv file.
Finally, you can save your data out in R format. This is useful to keep all the features of the data that you have worked on – for example, keeping factor orderings. Saving out the data as a text file would not preserve that information.
To read these data back into R you use the load() function. Once you do this, you can use ls() to check the names of the objects in your Workspace and use the loaded objects.
Run frequencies for the variable sibs (number of siblings). 1.What is the total number of cases? 2.What are the mean, median, range and standard deviation of this variable?
If you want to calculate the mean, median, range, and sd separately, you can use the following code (removing missing values before computation):
[1] 2348
[1] 2343
[1] 3.579599
[1] 3
[1] 0 25
[1] 2.863154
You can also get these values at once using the describe function in psych.
Create a new variable to represent the recodes of the variable hrs1 (number of hours worked in the last week) into less than 40 and more than 40 (two groups), and recode all missing values to NA. Be sure to check the new variable by creating a frequency table.
We can easily recode this variable by coding the categories as characters and converting them into a factor.
chr [1:2348] NA NA "More than 40" "More than 40" NA NA "Less than 40" ...
Factor w/ 2 levels "Less than 40",..: NA NA 2 2 NA NA 1 2 2 2 ...
Note that we skipped coding the numeric values of this variable, but when we converted it to a factor, R automatically created numeric values for us.
Comparing the the number of observations and NAs in each variable, we can ensure that the variable recode was performed correctly.
Find out how many foreign-born and native-born survey respondents can speak a language other than English. That is, run a crosstab using variables othlang (Can respondent speak a language other than English?) and born (Was respondent born in this country?).
Cell Contents
|-------------------------|
| Count |
| Column Percent |
|-------------------------|
========================================
gssdata$born
gssdata$othlang no yes Total
----------------------------------------
no 85 1537 1622
28.1% 75.2%
----------------------------------------
yes 217 506 723
71.9% 24.8%
----------------------------------------
Total 302 2043 2345
12.9% 87.1%
========================================
Create a bar chart for the variable neisafe. This variable is based on the question, “How safe interviewer thinks neighborhood is?” . The answers are categorized as: very safe, somewhat safe, somewhat unsafe, very unsafe. Include the title “Interviewer’s Perception for Neighborhood Safety”.
somewhat safe somewhat unsafe very safe very unsafe
805 191 1322 22
To draw the bar chart for a variable in the data frame, we can create a table object, which can be used as the first parameter in the barplot() function. The main and xlab arguments of this function are used to display the main title and the x-axis title, respectively.
To reorder the categories we use the factor() function.
First look at the levels:
[1] "somewhat safe" "somewhat unsafe" "very safe" "very unsafe"
somewhat safe somewhat unsafe very safe very unsafe
805 191 1322 22
very safe somewhat safe somewhat unsafe very unsafe
1322 805 191 22