R I

Getting Started with R

Training Session Date

Tue. Sep 29, 2026 – 6:00 pm

After attending this training session, you will be able to:

  1. Use Basic R syntax
  2. Use Common R packages
  3. Import datasets from other software such as SPSS, EXCEL, and Stata
  4. Compute new variables and recode variables
  5. Create frequency and contingency tables
  6. Obtain univariate statistics
  7. Create graphics and charts
  8. Save and export output

Introduction

Code and Dataset

For this training session, please download the following data:

What are R and RStudio?

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/.

Note

To use RStudio, you must first install R on your computer.

Download page for RStudio, Oct. 2026

What is the General Social Survey (GSS)?

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.

Starting R / RStudio

To launch RStudio, click on the start icon in the lower left-hand corner of the screen. Select RStudio from the list of programs.

RStudio Interface

The RStudio interface consists of four panes by default: the Script Editor, the Console, the Workspace pane, and the Viewer.

The RStudio interface.

The Menu Bar has pull-down menus that display additional commands when clicked.

Screenshot of the top toolbar in RStudio IDE on Windows.

R Console and Script Editor

Console

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:

10 - 8
[1] 2
23 * 2
[1] 46
5 / 5
[1] 1
log(90)
[1] 4.49981

You can use the up or down arrow keys (↑ and ↓) on the keyboard to cycle through previously entered commands and re-run them.

Scripts

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.

The New File button in RStudio.

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:

# This opens the R help documentation
help.start()

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).

Workspace and Viewer Panes

Workspace Pane

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.

RStudio Environment tab showing a data frame named "my.data" in the Global Environment.

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.

Viewer Pane

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:

?plot

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:

# setting a "seed" lets us generate the same "random" numbers each time we run the code
set.seed(2451) 
x <- c(1:6) # define a vector, x
y <- x + runif(6) # define the vector y as a function of x
            # plus random draws from the uniform distribution
plot(x, y)

Scatter plot with six data points showing a positive correlation between variables x and y.

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.

General Tips for Console

There are a few tips to keep in mind when using the Console:

  • R commands are case-sensitive. If you accidentally enter Plot() or PLOT() instead of plot(), you will get an error message stating that R could not find that function.
  • The angle bracket at the beginning of the line (>) 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.
  • Generally, you should type one command on each line. It is, however, possible to enter two or more commands on the same line, separated by a semicolon (;). Example: print("hi"); print("bye")
  • You can use either single quotation marks (') 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.
  • ↑ (Up Arrow) steps backward through the command history and ↓ (Down Arrow) steps forward through the command history.
  • The TAB key automatically completes a partially typed variable name or function; it can also prompt function arguments.
  • Ctrl + L will clear the R Console. This will not delete objects in the environment (in memory).
  • The ESC key will stop the execution of a command.
  • Some function arguments require quotation marks and others do not. For example, typing install.packages(spdep) instead of install.packages("spdep") will return an error. Check the syntax for the function you are using.
  • Incorrect use of slashes can be a common source of errors in R. R always uses forward slashes for file paths and backslash as an escape character.
  • For example, to specify a file path you must use Data/raw/myfile.csv instead of Data\raw\myfile.csv (even though Windows normally uses backslashes for file paths).
  • To write text that spans multiple lines, you would use \n at the end of the line, which means “new line”, e.g., cat("This is the first line.\nThis is the second line.")

Packages and Library

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:

  • Use the function install.packages("packagename")
  • Click Tools > Install Packages… in the menu bar.
  • Go to the Packages tab in the Viewer pane, click on Install, and type the name of the package you want to install.

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.

Important

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.

Function help documentation

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.

  • To learn more about a function, use help(functionName), or ?functionName.
  • To learn more about a function in a specific package, you can use the syntax help(functionName, package="packageName") or ?packageName::functionName.
  • If the function you’re looking for doesn’t show up on the first try, you can use the ?? 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.

Data Management

Working with Directories

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().

> getwd()
 [1] "C:/Windows/Users/YourNetId/Documents" 

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.

TipRStudio Projects

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.

RStudio with the 'Session' menu open. The 'Set Working Directory' option is highlighted, and 'To Source File Location' is selected, setting the working directory to the location of the current script.

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.

setwd("C:/Users/YourNetId/Desktop/RI")
list.files()
 [1] "test.txt"
list.files("C:/Users/YourNetId/Desktop/RI")
 [1] "test.txt"

Data Structures

Vectors

The c() function concatenates (combines) values into a vector.

Usage: P <- c(X,Y,Z, ...)

a <- c(1,2,5.3,6,-2,4)
a
[1]  1.0  2.0  5.3  6.0 -2.0  4.0
b <- c("male", "female")
b
[1] "male"   "female"

Matrices

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)

a1 <- c(1,2,3,4,5,6)
mat1 <- matrix(a1, nrow=2, ncol=3,
              dimnames=list(
                c("R1","R2"),
                c("C1","C2","C3")
              ))
mat1
   C1 C2 C3
R1  1  3  5
R2  2  4  6

Data Frames

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...)

a1 <- c(1,2,3,4,5,6)
a2 <- c("a","b","c","d","e","f")
df <- data.frame(a1,a2)
df
  a1 a2
1  1  a
2  2  b
3  3  c
4  4  d
5  5  e
6  6  f

Lists

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...)

a1 <- c(2, 3, 5)
a2 <- c("aa", "bb", "cc", "dd", "ee")
a3 <- 15
myList <- list("mylist", a1, a2, a3)
myList
[[1]]
[1] "mylist"

[[2]]
[1] 2 3 5

[[3]]
[1] "aa" "bb" "cc" "dd" "ee"

[[4]]
[1] 15

Factors

Factors are used to encode a numeric vector into a categorical or ordinal variable.

Usage: myFactor <- factor(data)

a1 <- c(1, 2, 1, 2, 1, 3, 3)
myFactor <- factor(a1)
myFactor
[1] 1 2 1 2 1 3 3
Levels: 1 2 3

The output displays the factor values.

Importing Data

Importing From a Delimited Text File

RStudio showing code that reads a text file into a data frame called mydata using read.table().

The Data Editor window displays a table.

Importing From a .csv or Text File

The read.csv() function reads a .csv file and sets it as the data object.

Example:

 gssdata <- read.csv("R_Data.csv", header = TRUE, 
 na.strings = c("", "NA"), stringsAsFactors = FALSE)
  • Because we already set our working directory, we can provide just the file name ("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.
  • Note: Some people prefer using the 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):

gssdata <- read.csv("R_Data.csv", header=TRUE,
 na.strings = c("", "NA"), stringsAsFactors = FALSE)

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).

Importing From an Excel File

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.

    library(readxl)
    xldata <- read_excel("my_excel_data.xlsx", range = "C1:E7")

Importing From Another Format

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:

library(haven)
gssdata <- read_dta("StataGSSData.dta")

Data Manipulation and Transformation

Viewing Data

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:

gssdata$educ
   [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:

names(gssdata)
 [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.

str(gssdata)
'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.

Data editor window displaying the gssdata dataset in tabular format.

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.

Data editor window displaying the gssdata dataset in tabular format.

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.

Other Useful Functions For Working with Imported Data

dim(object) – Displays dimensions of an object.

dim(gssdata)
[1] 2348   37

head(object) – Get the first several lines of an object.

head(gssdata)
  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.

tail(gssdata)
       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

Descriptive Statistics

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).

Summary statistics

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:

library(psych)
describe(gssdata$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

Exercise 1

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?

Frequencies

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.

library(descr)
freq(gssdata$sex)

gssdata$sex 
       Frequency Percent
female      1296    55.2
male        1052    44.8
Total       2348   100.0

Bar chart comparing two categories: 'female' and 'male.'

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).

freq(gssdata$nextgen)

gssdata$nextgen 
                  Frequency Percent Valid Percent
agree                   624  26.576        52.525
disagree                 76   3.237         6.397
strongly agree          455  19.378        38.300
strongly disagree        33   1.405         2.778
NA's                   1160  49.404              
Total                  2348 100.000       100.000
sum(is.na(gssdata$nextgen))
[1] 1160

Data Transformation

Creating New Variables

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.

gssdata$sqrtage <- sqrt(gssdata$age)
gssdata$age[1:10]
 [1] 43 74 42 63 71 67 59 43 62 55
gssdata$sqrtage[1:10]
 [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:

sqrtage
Error:
! object 'sqrtage' not found

The above codes create a new variable sqrtage by calculating the square root of the existing age variable.

Tip

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.

Recoding Variables

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:

  • Change an existing categorical variable into a new categorical variable with fewer categories/levels.
  • Change an existing continuous variable with many unique values (for example, 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).
  • Code missing values.
  • Replace miscoded values with correct values.
  • Create a dummy variable upon a cutoff value.
Tip

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”.

gssdata$agecat[gssdata$age > 75] <- "Elder"
gssdata$agecat[gssdata$age > 45 & gssdata$age <= 75] <- "Middle Aged"
gssdata$agecat[gssdata$age <= 45] <- "Young"
gssdata$agecat[1:10]
 [1] "Young"       "Middle Aged" "Young"       "Middle Aged" "Middle Aged"
 [6] "Middle Aged" "Middle Aged" "Young"       "Middle Aged" "Middle Aged"
class(gssdata$agecat)
[1] "character"

We can see this new variable in the Data Editor,

A spreadsheet titled gssdata displayed in a data analysis environment.

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.

gssdata$agecat2 <- factor(gssdata$agecat,
 levels=c("Young","Middle Aged","Elder"))

head(gssdata$agecat2)
[1] Young       Middle Aged Young       Middle Aged Middle Aged Middle Aged
Levels: Young Middle Aged Elder
class(gssdata$agecat2)
[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.

str(gssdata$agecat2)
 Factor w/ 3 levels "Young","Middle Aged",..: 1 2 1 2 2 2 2 1 2 2 ...
levels(gssdata$agecat2)
[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.

table(gssdata$agecat2, useNA="ifany")

      Young Middle Aged       Elder        <NA> 
       1077        1079         185           7 

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.

elderdata <- subset(gssdata, gssdata$age>75)
dim(elderdata)
[1] 185  40
middleAgeddata <- subset(gssdata, (gssdata$age > 45
 & gssdata$age <= 75) )
dim(middleAgeddata)
[1] 1079   40
youngdata <- subset(gssdata, gssdata$age <= 45)
dim(youngdata)
[1] 1077   40

Exercise 2

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.

Multivariate Tables

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.

table(gssdata$sex, gssdata$postlife)
        
           no  yes
  female  161 1017
  male    242  703
table(gssdata$sex, gssdata$postlife, useNA="ifany")
        
           no  yes <NA>
  female  161 1017  118
  male    242  703  107

crosstab() or CrossTable()

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.

crosstab(gssdata$sex, gssdata$postlife)

   Cell Contents 
|-------------------------|
|                   Count | 
|-------------------------|

==================================
               gssdata$postlife
gssdata$sex      no    yes   Total
----------------------------------
female          161   1017    1178
----------------------------------
male            242    703     945
----------------------------------
Total           403   1720    2123
==================================

Plot showing the relationship between gender and belief in postlife.

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:

# column percentage
crosstab(gssdata$sex, gssdata$postlife, prop.c = TRUE)

   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%        
====================================

Exercise 3

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?).

Graphics

Histogram

A histogram visually displays the distribution of a continuous variable. In R, the hist() function works as shown below:

hist(gssdata$age, main='Age Distribution', xlab='Age')

Histogram titled "Age Distribution" showing how many individuals fall into different age ranges.

Bar Graph

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:

countSex <- table(gssdata$sex)
barplot(countSex, main="Gender Distribution",
 xlab="Gender", ylim=c(0, 2000))

Bar chart titled "Gender Distribution" showing counts for two categories: "female" and "male."

Exercise 4

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”.

Grouped Bar Graph

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:

counts <- table(gssdata$sex, gssdata$marital)

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.

counts <- table(gssdata$sex, gssdata$marital)
barplot(counts,
         main= 'Distribution by sex and marital status',
         xlab = 'Marital status by sex',
         ylim = c(0,800),
         legend = rownames(counts), beside = TRUE)

Bar chart titled "Distribution by sex and marital status" showing how marital status varies between females and males.

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:

# reorder categories
table(gssdata$marital)

     divorced       married never married     separated       widowed 
          403           998           670            75           200 
gssdata$marital2 <- factor(gssdata$marital,c("never married","married",
   "separated","divorced","widowed"))

#ggplot2 way
library(ggplot2)

Attaching package: 'ggplot2'
The following objects are masked from 'package:psych':

    %+%, alpha
ggplot(data=subset(gssdata,!is.na(gssdata$marital2)),
        aes(marital2,fill=sex)) +
   geom_bar(position="dodge") +
   scale_fill_grey() +
   xlab("Marital Status by Sex") +
   theme_minimal()

Bar chart titled 'Distribution by sex and marital status' showing how reordered marital status varies by gender.

Scatterplot

A scatterplot plots the “positions” of two variables in dimensions x and y. We run the plot() function:

plot(gssdata$age, gssdata$educ, main = "Scatterplot Example",
 xlab = "Age", ylab = "Education")

Scatterplot titled "Scatterplot Example" showing individual data points representing education level plotted against age.

Here’s the plot using ggplot2, filling the points and fitting linear regression lines by sex:

library(ggplot2)
ggplot(gssdata, aes(x = age, y = educ, color = sex)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  xlab("Age") +
  ylab("Education") +
  ggtitle("Scatterplot Example by Sex") +
  theme_bw()
`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.

Note

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.).

Scatterplot titled "Scatterplot example by sex" showing individual data points for age and education, color-coded by sex—red for females and blue for males.

Saving and Printing

Output data can be exported to many different file formats. For example:

write.table(gssdata, file = "SAVE_OUT_Example_GSS.txt",
             append = FALSE, sep = ",")

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.

write.csv(gssdata, file = "SAVE_OUT_Example_GSS.csv", row.names=F)

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.

save(gssdata, file="SAVE_OUT_Example_GSS.RData")

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.

load("SAVE_OUT_Example_GSS.RData")

Appendix: Exercises and Answers

Exercise 1

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?

Answer

If you want to calculate the mean, median, range, and sd separately, you can use the following code (removing missing values before computation):

length(gssdata$SIBS)
[1] 2348
# without nas:
sum(!is.na(gssdata$SIBS))
[1] 2343
mean(gssdata$SIBS, na.rm = TRUE)
[1] 3.579599
median(gssdata$SIBS, na.rm = TRUE)
[1] 3
range(gssdata$SIBS, na.rm = TRUE)
[1]  0 25
sd(gssdata$SIBS, na.rm = TRUE)
[1] 2.863154

You can also get these values at once using the describe function in psych.

library(psych)
describe(gssdata$SIBS)
   vars    n mean   sd median trimmed  mad min max range skew kurtosis   se
X1    1 2343 3.58 2.86      3    3.17 2.97   0  25    25 1.75     5.36 0.06

Exercise 2

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.

Answer

We can easily recode this variable by coding the categories as characters and converting them into a factor.

gssdata$recodeHrs <- NA
gssdata$recodeHrs[gssdata$hrs1 < 40 & gssdata$hrs1 >= 0] <- "Less than 40"
gssdata$recodeHrs[gssdata$hrs1 >= 40] <- "More than 40"
str(gssdata$recodeHrs)
 chr [1:2348] NA NA "More than 40" "More than 40" NA NA "Less than 40" ...
gssdata$recodeHrs <- factor(gssdata$recodeHrs)

str(gssdata$recodeHrs)
 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.

descr(gssdata$recodeHrs)
Less than 40 More than 40          NAs 
         419          962          967 
freq(gssdata$recodeHrs)

gssdata$recodeHrs 
             Frequency Percent Valid Percent
Less than 40       419   17.84         30.34
More than 40       962   40.97         69.66
NA's               967   41.18              
Total             2348  100.00        100.00

Exercise 3

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?).

Answer

crosstab(gssdata$othlang, gssdata$born, prop.c=TRUE)

   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%        
========================================

Exercise 4

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”.

Answer

neisafe_table = table(gssdata$neisafe)
neisafe_table

  somewhat safe somewhat unsafe       very safe     very unsafe 
            805             191            1322              22 

Bar chart titled "Interviewer's Perception for Neighborhood Safety" showing how interviewers rated neighborhood safety in four categories.

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:

gssdata$neisafe <- factor(gssdata$neisafe)
levels(gssdata$neisafe)
[1] "somewhat safe"   "somewhat unsafe" "very safe"       "very unsafe"    
table(gssdata$neisafe)

  somewhat safe somewhat unsafe       very safe     very unsafe 
            805             191            1322              22 
## or reordered:
gssdata$neisafe2 <- factor(gssdata$neisafe,
                            c("very safe", "somewhat safe",
                            "somewhat unsafe","very unsafe"))

neisafe_table_ordered<-table(gssdata$neisafe2)
neisafe_table_ordered

      very safe   somewhat safe somewhat unsafe     very unsafe 
           1322             805             191              22 
barplot(neisafe_table_ordered,
main = "Interviewer's Perception for Neighborhood Safety",
xlab = "How safe interviewer thinks neighborhood is?")

Bar chart titled "Interviewer's Perception for Neighborhood Safety" showing how interviewers rated neighborhood safety in four categories in the specified order.

Back to top