10 - 8[1] 2
23 * 3[1] 69
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. As statistical software, 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 and R are both free for download from the Posit website https://posit.co/download/rstudio-desktop/.
To use RStudio, you must first also install R on your computer. In the next section, we will navigate through the RStudio environment.
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 environment consists of four basic elements by default: the Script Editor, the Console, the Workspace pane, and the Viewer.
The Menu Bar has pull-down menus that when clicked will display additional commands.
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 functions and data transformations that you don’t want to save in a script.
Go to the R Console command line and type in a basic mathematical function, such as 10-8, 23*2, 5/5 or log(90).
After each function, press ENTER.
The results should appear as below:
Several commands at once can also be written in the R Script Editor and then submitted. In an R session, you cannot save commands written in the console. You can use ↑ and ↓ on the keyboard to cycle through previously entered commands. Sometimes, you will need to perform a fairly complex analysis that consists of a series of commands. In such cases, you will want to write your commands in the script editor so that you can save it for future review or to re-run the commands at a later time.
To create a new script in RStudio, click on the New File button in the upper left hand corner of RStudio. Then click on R Script to create a new empty R Script.
A green plus icon for creating new files is visible.
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.See the example below:
To execute a command written in the Script Editor, place the cursor on the command line, and then type Ctrl + Enter (Cmd + Enter on Mac). The executed command will also appear in the R Console.
To run multiple lines of script at once, highlight the desired lines and use the same command.
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 using the coderemove(list=ls()).
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 submit a help request, typing ?plot.
Remember to press Enter to execute a typed command (or Ctrl+Enter if working in the Script Editor). Information about the plot function should be displayed.
Now let’s display something in the Plot tab of the Viewer pane.
In the script editor (or in the console), type:
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:
Help.start() instead of help.start(), you will get an error message stating that R could not find that function.> is the R prompt. If you do not complete a command, you will see + at the end of a line. To complete the command, just add the remaining element of the command directly after the + sign.;). Example: print("hi");print("bye")install.packages(spdep) instead of** install.packages("spdep") will return an error. Check the syntax for the function you are using.setwd("c://mydata") instead of setwd("c:\mydata").R is equipped with a standard set of packages. The primary contents of packages are functions and data. The library is the directory where packages are located. In addition to the standard set of packages, many other packages are available for download and installation. The number of R packages is constantly increasing due to many contributors within the R community. Additional R packages may be used for a specific statistical analysis that otherwise is impossible or much harder to do with standard R packages (for example, spatial analysis) or can have other functions such as creating more attractive and flexible plots. In short, adding other packages allow us to perform a greater variety of types of analysis.
To install a package, use the command install.packages("packagename"). Try to install the package foreign. You generally only need to install packages once on a computer.
Once packages are installed, they need to be loaded each time you want to use them in an R session. You can load packages by typing library(packageName) (e.g. library(foreign)). We recommend loading packages all at once in the beginning of your R script.
Once a package is loaded, more information about the package can be obtained by typing library(help=packageName) or by searching for or locating the package under the Packages tab of the Viewer pane. Continuing with our foreign package example, type library(help=foreign). This will open a window in the R environment which displays the documentation for the foreign package. If you wish to learn more about a particular function in a package you may enter help(functionName). Entering help(read.csv) will open a new page in the Help tab of the Viewer pane showing the R documentation for the read.csv function in the foreign package. The command 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 R, a standard working directory is set by default depending on your operating system. To see which directory is active in the current session, type and enter the command getwd().
To change the working directory to your desired location (e.g. where your data files are located), you can either a) set it via code or b) use the R Session menu. To change via code, simply enter the desired destination as a string (inside quotation marks).
After typing and entering setwd("C:/Users/YourNetId/Desktop/RI"), the current working directory is changed to "C:/Users/YourNetId/Desktop/RI".
To change via the Session 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.
The command list.files() produces 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 command c() combines the submitted values into a vector or list.
Usage: P = c(X,Y,Z, ...)
The command matrix() creates a matrix from a given set of values.
Usage: matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
Data frames are also 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 generic vector containing different objects. The objects in a list can be different types and dimensions.
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() command reads a .csv file and sets it as the data object.
Example:
The read.csv() function includes parameters to treat empty strings and “NA” as missing values, and prevents automatic conversion of strings to factors.
In read.csv(), header=TRUE lets R know 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.string=c("", "NA") tells the function that both the empty strings or the NA string should be treated as missing (NA).
Because we already set our working directory, we do not need to specify the full (absolute) path to the file, just the file name. If the file is in the working directory, it will be imported.
For the rest of this notebook, we load the training dataset the same way, using the R_Data.csv file you downloaded above (and placed in your working directory):
The stringsAsFactors = FALSE argument is often used in functions like read.csv(), and read.table() to prevent character strings from being automatically converted to factors in R.
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).
Data can be viewed by clicking on the name of the data frame in the Environment tab of the Workspace pane.
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 data are not ‘’tidy’’.
R can import data from SPSS, SAS, and STATA formats using similar methods. You may need to import a package such as haven or foreign to import those formats. For more details, please look up R help. Example:
This section explains some frequently used commands to view or grab information about the data.
dataObject$variableName: Displays the vector defined by the variableName contained in the dataObject. Also 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 read.csv command. Therefore, as shown, the command to list variable names in the data is 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. We will use gssdata as an example. Submitting the command str(gssdata), we see that it contains 37 variables (which matches the output from names(gssdata). The variables are numeric, factors (categorical), and integers. Variables can also be strings – characters which do not represent categories.
'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 ...
View(dataObject) Opens dataObject in the Script pane. Can also be accessed by clicking on the name of the object in the Environment tab of the Workspace pane.
fix(dataObject): Launches the Data Editor and opens dataObject.
In the Data Editor, you can browse the spreadsheet by scrolling up/down or using the arrow keys. You can also edit data. For example, you might want to change the value of the seventh case of the education variable, educ. To do this, you would move the cursor to the appropriate cell and double-click.
If you need to change a variable name and/or its associated data type, just click the variable of interest on top of the spreadsheet and you will get the variable editor dialog box as follows.
NOTE: Changes you make in the Data Editor will not be saved to your data file! To save these changes, you will need to use write.csv() or a similar function.
attach(dataObject)/ detach(dataObject): Attaches/Detaches a set of R objects to a search path. When a database is attached to the R search path, it means that the database is searched by R when evaluating a variable, so objects in the database can be accessed by simply giving their names. If a database has not been attached, then the variables it contains must be accessed using the $ notation.
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
In this section, we will introduce several basic statements in descriptive statistics. In the R environment, many packages are not loaded into the console by default and need to be loaded by using the Library() statement.
For instance, you can get concise statistical description of the data using the describe function in the psych package. However, the psych package is not loaded by default. As previously explained (see the “Packages and Library” sub-section in this workbook), it means that you first need to install and load the psych package before you can use any of the functions included in the package.
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). 1. What is the total number of cases? 2. What are the mean, median, range and standard deviation of this variable?
Categorical (factor) variables can be summarized in R using frequency and proportion tables. The freq() function prints a frequency table of the selected object. This method is in the descr package, which you may need to install. A bar chart associated with the frequency table will also pop up.
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 <- or =. 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.
The recode procedure transforms an existing variable into a new variable by changing, rearranging, or consolidating the values of the existing variable. It allows the user to:
Change an existing categorical variable into a new categorical variable with a fewer number of 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 will have low, medium, and high as values, ageRecode will have young, adult, senior as values).
Code missing values.
Replace miscoded values with correct values.
Create a dummy variable upon a cutoff value.
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:
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.
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: Elder, Middle Aged, and Young. You can double how R recognizes agecat2 by using the str() or levels() functions.
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() command.
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 command subset() 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 39
[1] 1079 39
[1] 1077 39
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(), or CrossTable(), function creates a crosstab, which allows you to compare two or more categorical variables. The crosstab command is easier to use and more sophisticated than the base R table() command. It allows for chi-squared tests and other more specialized outputs. In order to use this command, you must first install the library descr. Once installed, establish it as the package in use: library(descr). Again, to learn about the commands within this library you can enter library(help=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() command 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 for 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.
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