Chapter 3 Objects and Variables
What You’ll Learn:
- How R stores and finds objects
- The most common beginner errors
- Understanding R’s case sensitivity and naming rules
- Scoping basics that prevent errors
Key Errors Covered: 10+ object-related errors
Difficulty: ⭐ Beginner
3.1 Introduction
Every R session starts with creating objects. And every R learner’s journey starts with object 'x' not found. This error is so universal that it deserves deep understanding.
Simple, right? Until it’s not. Let’s explore what goes wrong.
3.2 Error #1: object 'x' not found
⭐ BEGINNER 🔗 SCOPING
3.2.2 What It Means
R looked for an object named my_number in:
1. The current environment (.GlobalEnv)
2. All loaded packages (in search path order)
3. The base environment
…and couldn’t find it anywhere.
3.2.3 Common Causes
3.2.3.1 Cause 1: Typo in Object Name
my_variable <- 10
my_varaible + 5 # Notice the typo: varaible vs variable
#> Error: object 'my_varaible' not found💡 Key Insight: R is case-sensitive!
# These are THREE different objects:
myVariable <- 1
MyVariable <- 2
myvariable <- 3
ls() # All three exist
#> [1] "a" "A"
#> [3] "A_col" "A_inv"
#> [5] "A_sub" "acc1"
#> [7] "acc2" "account"
#> [9] "add" "add_10"
#> [11] "add_100" "add_3"
#> [13] "add_5" "add_column"
#> [15] "add_logging" "add_one"
#> [17] "add_scalar" "add_ten"
#> [19] "add_ten_global" "add_timing"
#> [21] "add_with_recycling" "after"
#> [23] "after_clean" "age"
#> [25] "age_collapsed" "age_groups"
#> [27] "ages" "ages_binned"
#> [29] "alice" "alice_s4"
#> [31] "all_data" "all_levels"
#> [33] "all_names" "all_products"
#> [35] "all_sizes" "analysis"
#> [37] "analysis_checklist" "analyze_strings"
#> [39] "anova_model" "anova_model2"
#> [41] "anova_model3" "anova_result"
#> [43] "apply_func" "arr"
#> [45] "assert_that" "attempt_counter"
#> [47] "audit_columns" "auto"
#> [49] "automatic" "average_temperature"
#> [51] "average_value" "avg_temperature"
#> [53] "avgTemperature" "b"
#> [55] "B" "B_matched"
#> [57] "B_reshaped" "B_sub"
#> [59] "bad" "bad_data"
#> [61] "bad_list" "before"
#> [63] "before_clean" "big_numbers"
#> [65] "big_ones" "c"
#> [67] "C" "calculate"
#> [69] "calculate_discount" "calculate_ltv"
#> [71] "calculate_mean" "calculate_price"
#> [73] "calculate_ratio" "calculate_safe"
#> [75] "calculate_total" "calculator"
#> [77] "can_multiply" "capitalize"
#> [79] "careful_sqrt" "cars_grouped"
#> [81] "cars_rds" "cars_tbl"
#> [83] "ch" "char"
#> [85] "char_vec" "chars_each"
#> [87] "check_and_subset" "check_factor_for_modeling"
#> [89] "check_file_writable" "check_function_variables"
#> [91] "check_grouped_operations" "check_grouping"
#> [93] "check_join_keys" "check_matrix_ops"
#> [95] "check_pipeline" "check_variation"
#> [97] "circle_area" "classify_grade"
#> [99] "classify_grade_detailed" "clean"
#> [ reached 'max' / getOption("max.print") -- omitted 674 entries ]3.2.3.2 Cause 2: Never Created the Object
# Forgot to run this line:
# result <- 100 * 2
# Trying to use it:
result / 4
#> [1] 0.25 1.00 2.25 4.00 6.25 9.00 12.25 16.00 20.25
#> [10] 25.00 30.25 36.00 42.25 49.00 56.25 64.00 72.25 81.00
#> [19] 90.25 100.00 110.25 121.00 132.25 144.00 156.25 169.00 182.25
#> [28] 196.00 210.25 225.00 240.25 256.00 272.25 289.00 306.25 324.00
#> [37] 342.25 361.00 380.25 400.00 420.25 441.00 462.25 484.00 506.25
#> [46] 529.00 552.25 576.00 600.25 625.00 650.25 676.00 702.25 729.00
#> [55] 756.25 784.00 812.25 841.00 870.25 900.00 930.25 961.00 992.25
#> [64] 1024.00 1056.25 1089.00 1122.25 1156.00 1190.25 1225.00 1260.25 1296.00
#> [73] 1332.25 1369.00 1406.25 1444.00 1482.25 1521.00 1560.25 1600.00 1640.25
#> [82] 1681.00 1722.25 1764.00 1806.25 1849.00 1892.25 1936.00 1980.25 2025.00
#> [91] 2070.25 2116.00 2162.25 2209.00 2256.25 2304.00 2352.25 2401.00 2450.25
#> [100] 2500.00
#> [ reached 'max' / getOption("max.print") -- omitted 900 entries ]3.2.4 Solutions
✅ SOLUTIONS
1. Check spelling carefully:
2. Verify object exists:
# List all objects
ls()
#> [1] "a" "A"
#> [3] "A_col" "A_inv"
#> [5] "A_sub" "acc1"
#> [7] "acc2" "account"
#> [9] "add" "add_10"
#> [11] "add_100" "add_3"
#> [13] "add_5" "add_column"
#> [15] "add_logging" "add_one"
#> [17] "add_scalar" "add_ten"
#> [19] "add_ten_global" "add_timing"
#> [21] "add_with_recycling" "after"
#> [23] "after_clean" "age"
#> [25] "age_collapsed" "age_groups"
#> [27] "ages" "ages_binned"
#> [29] "alice" "alice_s4"
#> [31] "all_data" "all_levels"
#> [33] "all_names" "all_products"
#> [35] "all_sizes" "analysis"
#> [37] "analysis_checklist" "analyze_strings"
#> [39] "anova_model" "anova_model2"
#> [41] "anova_model3" "anova_result"
#> [43] "apply_func" "arr"
#> [45] "assert_that" "attempt_counter"
#> [47] "audit_columns" "auto"
#> [49] "automatic" "average_temperature"
#> [51] "average_value" "avg_temperature"
#> [53] "avgTemperature" "b"
#> [55] "B" "B_matched"
#> [57] "B_reshaped" "B_sub"
#> [59] "bad" "bad_data"
#> [61] "bad_list" "before"
#> [63] "before_clean" "big_numbers"
#> [65] "big_ones" "c"
#> [67] "C" "calculate"
#> [69] "calculate_discount" "calculate_ltv"
#> [71] "calculate_mean" "calculate_price"
#> [73] "calculate_ratio" "calculate_safe"
#> [75] "calculate_total" "calculator"
#> [77] "can_multiply" "capitalize"
#> [79] "careful_sqrt" "cars_grouped"
#> [81] "cars_rds" "cars_tbl"
#> [83] "ch" "char"
#> [85] "char_vec" "chars_each"
#> [87] "check_and_subset" "check_factor_for_modeling"
#> [89] "check_file_writable" "check_function_variables"
#> [91] "check_grouped_operations" "check_grouping"
#> [93] "check_join_keys" "check_matrix_ops"
#> [95] "check_pipeline" "check_variation"
#> [97] "circle_area" "classify_grade"
#> [99] "classify_grade_detailed" "clean"
#> [ reached 'max' / getOption("max.print") -- omitted 673 entries ]
# Check if specific object exists
exists("my_variable")
#> [1] TRUE
# Search in environment
grep("var", ls(), value = TRUE) # Find objects with "var"
#> [1] "check_function_variables" "check_variation"
#> [3] "group_vars" "my_var"
#> [5] "my_variable" "my.variable"
#> [7] "myvariable" "other_var"3. Use RStudio’s autocomplete: - Type the first few letters - Press Tab to see available objects
4. Check your environment pane: In RStudio, look at the Environment pane (top-right) to see all objects.
5. Run all necessary code: Make sure you’ve executed all lines that create the objects you need.
6. Restart and run from top:
🎯 Best Practices
Use consistent naming: Choose a style and stick to it
snake_case(recommended for R)camelCase- Avoid
dot.case(can be confusing with S3 methods)
Meaningful names:
temperature_celsius>temp>tAvoid similar names:
# Confusing:
data1 <- ...
data2 <- ...
data_new <- ...
data_final <- ...
data_final2 <- ...
# Better:
raw_data <- ...
clean_data <- ...
analyzed_data <- ...- Run scripts top-to-bottom: Your script should work when run fresh
3.3 Error #2: could not find function "x"
⭐ BEGINNER 📦 PACKAGE
3.3.1 The Error
# Try to use a function from unloaded package
read_csv("data.csv")
#> Error: 'data.csv' does not exist in current working directory ('/Users/bioguo/Downloads/r_errors_book').🔴 ERROR
Error: could not find function "read_csv"
3.3.2 What It Means
R can’t find a function with that name. Functions are searched in: 1. The current environment 2. All loaded packages 3. NOT inside unloaded packages
3.3.3 Common Causes
3.3.3.2 Cause 2: Package Not Installed
Error in library(somepackage) :
there is no package called 'somepackage'
3.3.4 Solutions
✅ SOLUTIONS
1. Load the required package:
2. Install then load:
3. Use package::function notation:
# Use function without loading entire package
readr::read_csv("data.csv")
# Always works, no library() needed
dplyr::mutate(data, new_col = x + 1)4. Check function spelling:
# Base R uses dots
read.csv("data.csv") # Note the dot
# tidyverse uses underscores
library(readr)
read_csv("data.csv") # Note the underscore5. Remove conflicting object:
# If you accidentally overwrote:
mean <- 42 # Bad!
rm(mean) # Remove the object
mean(c(1, 2, 3)) # Now the function works
#> [1] 26. Find where function lives:
⚠️ Common Pitfall: Overwriting Functions
Never name objects after common functions:
Avoid naming objects:
- mean, sum, length, data, df, c, t, T, F
- matrix, list, vector, table
- plot, points, lines
- Any function you use regularly!
If you accidentally do it:
3.4 Error #3: unexpected symbol in "x"
⭐ BEGINNER 🔤 SYNTAX
3.4.1 The Error
my variable <- 10
#> Error in parse(text = input): <text>:1:4: unexpected symbol
#> 1: my variable
#> ^🔴 ERROR
Error: unexpected symbol in "my variable"
3.4.2 What It Means
R’s parser encountered something it didn’t expect. Usually a space or character where it shouldn’t be.
3.4.3 Common Causes
3.4.3.1 Cause 1: Space in Variable Name
3.4.3.2 Cause 2: Missing Operator
3.4.3.3 Cause 3: Two Statements on One Line
3.5 Error #4: unexpected '=' in "x"
⭐ BEGINNER 🔤 SYNTAX
3.5.3 Common Causes
3.5.3.1 Cause 1: Chained Assignment (doesn’t work like math)
3.5.4 Solutions
✅ SOLUTIONS
1. Use <- for assignment:
2. Use == for comparison:
3. Use = only in function arguments:
💡 Key Insight: <- vs =
# Both work for assignment:
x <- 10
x = 10
# But <- is preferred because:
# 1. Clearer intent (unambiguous assignment)
# 2. Works everywhere
# 3. R community standard
# = can be ambiguous:
mean(x = 1:10) # Named argument (good)
#> [1] 5.5
x = 1:10 # Assignment (works, but <- preferred)Best Practice: Use <- for assignment, = for function arguments
3.6 Error #5: object of type 'closure' is not subsettable
⭐⭐ INTERMEDIATE 🔢 TYPE
3.6.1 The Error
mean[1] # Trying to subset the mean function
#> Error in mean[1]: object of type 'closure' is not subsettable🔴 ERROR
Error in mean[1] : object of type 'closure' is not subsettable
3.6.2 What It Means
“Closure” = function. You’re trying to use [ on a function, which doesn’t make sense.
3.6.3 Common Causes
3.6.3.1 Cause 1: Forgot to Call the Function
3.6.4 Solutions
✅ SOLUTIONS
1. Call the function:
# Wrong:
data <- c(1, 2, 3)
result <- mean
result[1] # Error
#> Error in result[1]: object of type 'closure' is not subsettable
# Right:
result <- mean(data) # Call it
result # Number, can't subset but don't need to
#> [1] 22. Check if it’s a function:
3. Don’t overwrite function names:
3.7 Error #6: cannot change value of locked binding
⭐⭐ INTERMEDIATE 🔗 SCOPING
3.7.2 What It Means
You’re trying to modify a protected object. Some objects are locked to prevent accidental changes.
3.8 Understanding Variable Scope
💡 Key Insight: Where Variables Live
# Global environment
x <- 10
my_function <- function() {
# Function environment
y <- 20
# Can see global x
print(x)
# Can see local y
print(y)
}
my_function()
#> [1] 10
#> [1] 20
# Global can't see local yScoping Rules: 1. Look in current environment 2. Look in parent environment 3. Keep going up until found (or not)
3.9 Naming Conventions
🎯 R Naming Best Practices
Valid names:
# Letters, numbers, dots, underscores
my_variable
myVariable
my.variable
my_variable2
var_123
.hidden_var # Starts with dot (not shown by ls())Invalid names:
# Can't start with number
2var <- 10 # ERROR
# Can't have spaces
my var <- 10 # ERROR
# Can't use special characters
my-var <- 10 # ERROR (minus sign)
my$var <- 10 # ERROR
my@var <- 10 # ERRORReserved words (can’t use):
# These are taken:
if, else, repeat, while, function, for, in, next, break
TRUE, FALSE, NULL, Inf, NaN, NA, NA_integer_, NA_real_, NA_complex_, NA_character_Recommended style:
3.10 Summary
Key Takeaways:
- R is case-sensitive:
X≠x - Check spelling: Most “object not found” errors are typos
- Load packages: Functions need
library()or:: - Don’t overwrite functions: Avoid naming objects after functions
- Use
<-for assignment: Clearer than= - No spaces in names: Use
_or camelCase - Check environment: Use
ls()and RStudio’s Environment pane - Never use T/F: Always write TRUE/FALSE
Quick Fixes:
| Error | Likely Cause | Fix |
|---|---|---|
| object not found | Typo or not created | Check spelling, use ls() |
| function not found | Package not loaded | library() or package::function() |
| unexpected symbol | Space in name | Use _ instead |
| unexpected = | Used = instead of == | Use == for comparison |
| closure not subsettable | Forgot () on function | Add parentheses |
| locked binding | Tried to change T/F | Use different name |
3.11 Exercises
📝 Exercise 1: Spot the Errors
What’s wrong with each line?
📝 Exercise 2: Debug This Script
Fix all errors:
3.12 Exercise Answers
Click to see answers
Exercise 1:
# 1 - Space in name
my_result <- 100 # or myResult
# 2 - Typo in function name
Mean <- mean(c(1, 2, 3)) # OK (but confusing name)
mean(c(4, 5, 6)) # Fix: mean not meen
# 3 - Used = instead of ==
x <- 10
if (x == 10) print("yes")
# 4 - Overwrote c() function
my_vector <- c(1, 2, 3)
my_vector[1]
# 5 - Object 'data' doesn't exist (need to create first)
# Also need to create it before this line
# 6 - Can't change T
my_test <- FALSE # Use different nameExercise 2:
# Load data
my_data <- read.csv("results.csv") # Underscore, not space
# Calculate mean
average <- mean(my_data$value) # mean not Mean
# Compare
if (average == 50) { # == not =
print("Average is 50")
}
# Store result
is_above_50 <- average > 50 # Don't use TExercise 3: