Running Code and Locating Data
A survey count may need to be recalculated whenever a response is added or corrected. Writing the procedure as code lets us repeat the same decisions, but we must also be able to run those instructions with the intended inputs. This chapter establishes how to do that in R and Python. We begin with short calculations, save them in files called scripts, and examine how execution order and session state affect the results. We then use errors to diagnose failed calculations and establish how the session locates data files and makes installed packages available.
1.1 Working with data through code
How many people reported walking? The table below gives three answers to a question about yesterday’s activities. These answers were constructed for this example.
Table 1.1. Three constructed activity records.
person | activity |
|---|---|
| p1 | walking |
| p1 | Walking |
| p2 | reading |
Each row of Table 1.1 is a record of one answer. Two answers mention walking, and both came from p1. If we treat walking and Walking as the same activity, one person reported walking.
For a larger file, code can convert the labels to lowercase, select the rows labeled walking, and count each person once among those rows. Anyone can inspect those instructions and run them again when records are added or corrected. Code that counted the selected rows would give two every time for Table 1.1.
Two languages and one editor
This book writes such instructions in two languages, R and Python. Each has an interpreter, a program that runs code written in that language. Positron is the editor in which you write and run code for both languages. You install the languages separately from the editor.
The examples also use packages, collections of code that provide functions you can call by name. The R examples use the tidyverse collection of packages, and the Python examples use Polars. These packages must be installed for the interpreter that will run the examples.
Install R from the R Project, Python from python.org, and Positron from its download page, choosing the current stable release for your computer. Create a folder named book wherever you store your work and open it in Positron with File > Open Folder.
To start R, open the interpreter picker at the top right of the window, choose New Console Session, and select your R installation. The Console shows the R prompt, >, where you enter R code.
Enter the two lines below in the R Console, one at a time. The first installs tidyverse and its required packages from CRAN, the main repository of R packages. The second loads its core packages into the current R session and makes their functions available. A session is a running interpreter together with everything created in it so far. Install the packages once for this R installation, then load them in each new session that uses their functions.
1
2
install.packages("tidyverse")
library(tidyverse)
If the Console returns to > without an error, library(tidyverse) succeeded. A startup message may list filter() under Conflicts because two loaded packages provide functions with that name.
With book open in Positron, open View > Command Palette, choose Python: Create Environment, then choose Venv and select the Python you installed. Positron creates a folder named .venv inside book. This virtual environment stores the project’s Python packages apart from Python packages installed elsewhere on your computer.
Open the interpreter picker at the top right of the window, choose New Console Session, and select the Python interpreter in .venv. A session is a running interpreter together with the names created in it so far. If an R session is also open, assigning a name in one session does not define it in the other. With the Python session active, open the Command Palette, choose Packages: Install Package, search for polars, and select it from the results. Positron installs it into the active session’s environment, .venv. If Positron asks to restart the session, accept.
Enter the following line in the Python Console. It makes Polars available under the short name pl. A successful import returns to the >>> prompt without printing anything.
1
import polars as pl
The example data
Extract the book project’s example_data.zip inside book to create the folder book/data. The records are synthetic examples created for this book. The files in data/raw/ are the original exports. The files in data/practice/ are simpler to read and still contain spelling variants and missing-value codes. Use the files unchanged so you can repeat the examples with the same inputs.
The five bundles cover common kinds of social-science data. Their records represent different things, from individual task trials to district populations, as Table 1.2 shows.
Table 1.2. The five example bundles.
| Bundle | Setting | One record represents | Characteristic problem |
|---|---|---|---|
| Survey | An online questionnaire | One submitted response | One answer label can appear in several spellings |
| Experiment | A color-word reaction task on a lab computer | One task trial or one questionnaire record | Each person contributes many records |
| Panel | The same questionnaire at three waves | One person at one wave in the original files | Who takes part changes from wave to wave |
| Momentary assessments | Short questionnaires scheduled five times a day | A scheduled prompt in one file, a submitted response in another | An unanswered prompt has no matching response |
| District populations | An annual table of registered population | One district, with one column per year | The original report mixes titles, subtotals, and notes with district rows |
1.2 Expressions, results, and function calls
Before code can count records, we need to see what happens when one instruction runs. Type a line at the R prompt, >, or the Python prompt, >>>, and press Enter. The Console runs the line and shows what it produces. Why do 2 + 3 * 4 and (2 + 3) * 4 give different results?
In the R Console, enter 2 + 3 * 4. This is an expression, a piece of code that describes a calculation. To evaluate it, R multiplies 3 by 4 and then adds 2. The result is a value, in this case a number. Text is another kind of value. The marker [1] means that the first value on this line is item 1 of the result.
1
2 + 3 * 4
1
[1] 14
Parentheses can change the order. With (2 + 3) grouped together, R adds first and multiplies the sum by 4.
1
(2 + 3) * 4
1
[1] 20
The function abs() returns a number’s absolute value, its distance from zero. In abs(-3), the name abs identifies the function and -3 is its input, called an argument. The parentheses after abs call the function with that argument. In (2 + 3) * 4, the parentheses group the addition.
1
abs(-3)
1
[1] 3
A function can take more than one argument. In round(1.234, digits = 2), the first argument, the number to round, is matched to the function’s first input by its position. A comma separates it from the named argument digits = 2, which is matched by its name and requests two decimal places.
1
round(1.234, digits = 2)
1
[1] 1.23
In print("survey"), quotation marks tell R to treat survey as text. The print() function displays the value. R prints [1] before it and quotation marks around it. The text itself contains just the six letters in survey.
1
print("survey")
1
[1] "survey"
In the Python Console, enter 2 + 3 * 4. This is an expression, a piece of code that describes a calculation. To evaluate it, Python multiplies 3 by 4 and then adds 2. The number on the next line is the result. An expression can also produce other kinds of values, such as text.
1
2 + 3 * 4
1
14
Parentheses change which operation Python evaluates first. In the following expression, it adds 2 and 3, then multiplies the sum by 4.
1
(2 + 3) * 4
1
20
Python’s abs() function returns the absolute value of a number, its distance from zero. In abs(-3), abs names the function and -3 is the input, called an argument. The parentheses call the function with that argument. The call itself is an expression because it produces a value.
1
abs(-3)
1
3
In round(1.234, ndigits=2), round() takes the first argument, 1.234, as the number to round. After the comma, ndigits=2 asks for two decimal places. The first argument is identified by its position and the second by its name.
1
round(1.234, ndigits=2)
1
1.23
Quotation marks tell Python to treat survey as text. Passing that text to print() displays its characters without the quotation marks used in the code.
1
print("survey")
1
survey
1.3 Scripts, execution order, and session state
To repeat a calculation with a different input, we can give the input and result names and save the instructions in a script. The following example converts a response time from seconds to minutes. If you change 90 seconds to 120 in the saved script, how could the Console still show 1.5 minutes?
In R, <- assigns a value to a name. A name refers to an object, such as a number, a piece of text, or a function stored in the session. Each line below is one complete instruction, called a statement. Run all three in the R Console. The first assigns 90 to seconds without displaying it. The second looks up seconds, divides it by 60, and assigns the result to minutes. The third displays minutes.
1
2
3
seconds <- 90
minutes <- seconds / 60
print(minutes)
1
[1] 1.5
To save the three statements in an editable file, create a new file in Positron, enter them, and save it in the book folder as duration.R. The .R ending marks it as an R script, a plain text file of R instructions.
To run part of the file, place the cursor on a statement or select several lines and press Ctrl+Enter, or Cmd+Enter on macOS. Positron sends that code to the R Console. To run the whole file, choose R: Source R File from the Command Palette. The file stores instructions; the session stores the values produced when those instructions run.
Change line 1 of duration.R to seconds <- 120 and save the file without running that line. The first block shows the saved file. Run only lines 2 and 3, shown in the second block.
1
2
3
seconds <- 120
minutes <- seconds / 60
print(minutes)
1
2
3
# Run in the R Console: lines 2 and 3 only
minutes <- seconds / 60
print(minutes)
1
[1] 1.5
The result is 1.5 minutes, as before. The session has the value 90 for seconds, because the edited assignment has not run. Saving a change in the file does not execute it.
Run all three lines to obtain [1] 2, or two minutes. Then choose Interpreter: Restart Active Interpreter Session from the Command Palette. This clears the values assigned in the session but does not change the saved file or the installed packages. Try running only the conversion line.
1
2
# After the restart: line 2 only
minutes <- seconds / 60
1
Error: object 'seconds' not found
The error means that no object in the new session has the name seconds. Run the whole file with R: Source R File to assign that input before the conversion uses it. The result is [1] 2 again.
In Python, = assigns a value to a name. Numbers, text, and functions are examples of Python objects. The statement seconds = 90 makes the name seconds refer to the number 90 without displaying it. A statement is one complete instruction. The second statement looks up seconds, divides it by 60, and assigns the result to minutes. The third displays minutes. Inside a call such as round(1.234, ndigits=2), ndigits=2 passes an argument to the function.
1
2
3
seconds = 90
minutes = seconds / 60
print(minutes)
1
1.5
A Python script is a plain text file of Python statements. Save the three statements in the book folder as the script duration.py. With the Python session active, choose Python: Run Python File in Console from the Command Palette. Positron runs the file in the Python Console, and print() displays 1.5. Running a file adds the names that the file assigns to the session. It does not clear the names that the session already has, so values from earlier statements can be used afterward.
To test what saving changes, enter seconds = 90 in the Python Console. Set seconds = 120 on line 1 of duration.py and save it. The first block shows the saved file. Select only lines 2 and 3 and press Ctrl+Enter, or Cmd+Enter on macOS, to send them to the Console.
1
2
3
seconds = 120
minutes = seconds / 60
print(minutes)
1
2
3
# Run in the Python Console: lines 2 and 3 only
minutes = seconds / 60
print(minutes)
1
1.5
The displayed 1.5 uses the session’s value of 90. The new value of 120 is in the saved file, but its assignment has not run.
Run all three lines. The result of 120 / 60 is 2.0, or two minutes. Dividing these whole numbers with / gives a floating-point number, a type that can also represent fractions.
To check whether the saved instructions can produce that result without the existing values, choose Interpreter: Restart Active Interpreter Session to clear the names you assigned. Then run only the conversion line.
1
2
# After the restart: line 2 only
minutes = seconds / 60
1
NameError: name 'seconds' is not defined
No assignment to seconds has run in this new session. Run the whole file with Python: Run Python File in Console. The first line assigns 120 before the second uses it, so the script produces 2.0 even in a fresh session.
When a result disagrees with the code visible in the editor, check which statements actually ran in the current session. Running the whole script in a fresh session tests whether it depends on a value left over from an earlier run.
1.4 Reading errors and inspecting objects
After the restart, the session could not find seconds because its assignment had never run there. A misspelled name can produce a similar error even when the duration is available. In that case, the name in the error differs from the one in the assignment. To decide what to correct, we need to read the error message and inspect the input that the calculation actually received.
The assignment names the duration seconds, but the division uses the misspelled name secnds.
1
2
3
seconds <- 90
# Deliberate error: misspelled name
minutes <- secnds / 60
1
Error: object 'secnds' not found
The message names secnds. Spelling it seconds in the division matches the assignment.
1
2
minutes <- seconds / 60
print(minutes)
1
[1] 1.5
With the spelling corrected, seconds <- "90" gives the division text instead of a number.
1
2
3
seconds <- "90"
# Deliberate error: text where a number is needed
minutes <- seconds / 60
1
Error in seconds/60 : non-numeric argument to binary operator
R found seconds. This time the message concerns /, a binary operator with two inputs. One input is 60, a number, so the nonnumeric input must be the value stored in seconds. A value’s type indicates what kind of data it is, such as a number or text.
typeof() reports 90 as "double", R’s ordinary numeric type, and "90" as "character", its text type. typeof(seconds) shows which one the division received. Assigning 90 without quotes gives the division a number.
1
2
3
typeof(90)
typeof("90")
typeof(seconds)
1
2
3
[1] "double"
[1] "character"
[1] "character"
1
2
3
4
seconds <- 90
typeof(seconds)
minutes <- seconds / 60
print(minutes)
1
2
[1] "double"
[1] 1.5
A missing closing parenthesis causes a different kind of failure. In duration.R, remove the ) from print(minutes) on line 3, save the file, and run R: Source R File.
1
2
3
seconds <- 120
minutes <- seconds / 60
print(minutes
1
2
3
4
Error in source("duration.R") : duration.R:4:0: unexpected end of input
2: minutes <- seconds / 60
3: print(minutes
^
R reached the end of the file while the call to print() was still open. Before source() runs any lines, it parses the whole file, checking the structure of its instructions. The missing parenthesis prevents even the first assignment from running. Restore the parenthesis and run the file again to obtain [1] 2.
A function’s help can explain a result that seems unexpected even when the call succeeds. What does round(1.234) return if you omit digits? The usage line in help(round) gives the default, the value the function uses when you omit that argument.
1
help(round)
1
2
3
4
5
round(x, digits = 0, ...)
digits: integer indicating the number of decimal places ('round') or
significant digits ('signif') to be used. For 'round',
negative values are allowed (see 'Details').
With digits = 0, R rounds 1.234 to the nearest whole number, 1.
The assignment names the duration seconds, but the division uses the misspelled name secnds.
1
2
3
seconds = 90
# Deliberate error: misspelled name
minutes = secnds / 60
1
NameError: name 'secnds' is not defined. Did you mean: 'seconds'?
This NameError names secnds and suggests seconds, the name in the assignment. With that spelling, the division can use the stored value of 90.
1
2
minutes = seconds / 60
print(minutes)
1
1.5
With the spelling corrected, seconds = "90" gives the division text instead of a number.
1
2
3
seconds = "90"
# Deliberate error: text where a number is needed
minutes = seconds / 60
1
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Python found seconds, but / could not divide its value by 60. The two inputs to / are called its operands. The error gives the type of each operand, which tells you what kind of value it is. On the left, seconds is a str, or text. On the right, 60 is an int, or whole number.
type(90) and type("90") show how quotation marks change the type. type(seconds) shows that the stored duration has the same type as "90". Assigning 90 without quotes makes the division possible.
1
2
3
type(90)
type("90")
type(seconds)
1
2
3
<class 'int'>
<class 'str'>
<class 'str'>
1
2
3
4
seconds = 90
type(seconds)
minutes = seconds / 60
print(minutes)
1
2
<class 'int'>
1.5
In duration.py, remove the ) from print(minutes) on line 3, save the file, and run Python: Run Python File in Console.
1
2
3
seconds = 120
minutes = seconds / 60
print(minutes
1
2
3
4
File "duration.py", line 3
print(minutes
^
SyntaxError: '(' was never closed
The SyntaxError points to the unclosed parenthesis. Python checks the structure of the whole file before running it, so no line in this file executed. Restore the parenthesis and run the file again to obtain 2.0.
A function’s help can explain a result that seems unexpected even when the call succeeds. What does round(1.234) return if you omit ndigits? help(round) shows the function’s signature, the line listing its arguments and their defaults.
1
help(round)
1
2
3
4
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None.
Omitting ndigits uses its default, None, which means no number of decimal places was specified. Here round(1.234) returns the integer 1.
1.5 Paths, files, folders, and installed code
Restarting a session clears names such as seconds. The saved script and the survey file are still on disk, and the installed packages are still on the computer. Why can the Console find the survey from one folder and report it missing from another? Why must a package installed once be loaded again in each new session?
A path specifies a file’s location. Starting from book, the path data/practice/survey.csv goes through the folders data and practice to the file survey.csv. Forward slashes separate the names.
Make the R Console active. In Positron’s Explorer, open the context menu for book and choose Set as Working Directory in Active Console. The working directory is the folder that the session currently treats as its starting point. A relative path such as data/practice/survey.csv gives a location starting from that folder. getwd() displays that folder. file.exists() tests the survey path from there. The examples use /Users/alex/Documents/book on macOS. Your path depends on where you created book.
1
2
getwd()
file.exists("data/practice/survey.csv")
1
2
[1] "/Users/alex/Documents/book"
[1] TRUE
While the working directory is still book, normalizePath() gives the survey’s absolute path, starting at the top level of the file system. After setwd("data"), file.exists() tests both the relative path and that saved absolute path. The final setwd("..") returns to the containing folder, book.
1
2
3
4
5
6
7
8
9
survey_path <- normalizePath("data/practice/survey.csv")
survey_path
setwd("data")
getwd()
# Deliberate failure: the relative path now starts from data
file.exists("data/practice/survey.csv")
file.exists(survey_path)
setwd("..")
getwd()
1
2
3
4
5
[1] "/Users/alex/Documents/book/data/practice/survey.csv"
[1] "/Users/alex/Documents/book/data"
[1] FALSE
[1] TRUE
[1] "/Users/alex/Documents/book"
From book/data, the same relative path now points to book/data/data/practice/survey.csv. No file exists there, so the first check returns FALSE. file.exists(survey_path) still returns TRUE because the absolute path points to the original file.
Restart R with Interpreter: Restart Active Interpreter Session. Does the new session recognize the name tibble? exists("tibble") checks before and after library(tidyverse). find.package("tidyverse") locates the installed package, and R.home() locates the R installation running this session.
1
2
3
4
5
exists("tibble")
library(tidyverse)
exists("tibble")
find.package("tidyverse")
R.home()
1
2
3
4
[1] FALSE
[1] TRUE
[1] "/Library/Frameworks/R.framework/Resources/library/tidyverse"
[1] "/Library/Frameworks/R.framework/Resources"
The change from FALSE to TRUE shows that tibble() became available by name when library(tidyverse) attached the core packages. If loading fails in another session, compare its R.home() path with the path from the session where loading succeeded.
Make the Python Console active. In Positron’s Explorer, open the context menu for book and choose Set as Working Directory in Active Console. The working directory is where the session starts looking for a relative path such as data/practice/survey.csv.
Python represents file paths with objects provided by pathlib. This module, a collection of related Python code, is part of the standard library distributed with Python. from pathlib import Path makes Path available in this session.
Path.cwd() shows the working directory, and Path("data/practice/survey.csv") represents the survey path relative to that directory. A method is a function called through an object. Here survey_relative.exists() checks whether the file exists at that path.
1
2
3
4
from pathlib import Path
Path.cwd()
survey_relative = Path("data/practice/survey.csv")
survey_relative.exists()
1
2
PosixPath('/Users/alex/Documents/book')
True
On macOS, the working directory appears as a PosixPath object. Your path depends on where you created book. The result True confirms that the survey file can be found from this directory.
Changing the working directory lets us test whether a path depends on its starting point. While the current folder is still book, survey_relative.resolve() gives the survey’s absolute path, starting at the top level of the file system.
Python’s standard-library module os provides os.chdir() for changing the working directory. With import os, you call the function through the module name; the earlier from pathlib import Path made Path available directly. After os.chdir("data"), the two checks test the relative and absolute paths from the new directory. os.chdir("..") then returns to book.
1
2
3
4
5
6
7
8
9
10
import os
survey_absolute = survey_relative.resolve()
survey_absolute
os.chdir("data")
Path.cwd()
# Deliberate failure: the relative path now starts from data
survey_relative.exists()
survey_absolute.exists()
os.chdir("..")
Path.cwd()
1
2
3
4
5
PosixPath('/Users/alex/Documents/book/data/practice/survey.csv')
PosixPath('/Users/alex/Documents/book/data')
False
True
PosixPath('/Users/alex/Documents/book')
From book/data, the relative path now points to the nonexistent book/data/data/practice/survey.csv. That is why survey_relative.exists() returns False while survey_absolute.exists() still returns True.
Restarting Python does not remove the survey file or installed packages, but imported names must be defined again. Restart Python and enter pl in its Console.
1
2
# Deliberate failure in a fresh session: pl has not been imported
pl
1
NameError: name 'pl' is not defined
Polars is installed as a package, a collection of modules. This session can use the name pl once it runs import polars as pl. The standard-library module sys provides sys.executable, the path to the Python interpreter running the Console.
1
2
3
import polars as pl
import sys
sys.executable
1
'/Users/alex/Documents/book/.venv/bin/python'
Here the Console is using the Python in book/.venv. If import polars raises ModuleNotFoundError, you can still run import sys and inspect sys.executable to see whether you started the Python where you installed Polars.