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.

# Your first R command
x <- 42
x
#> [1] 42

Simple, right? Until it’s not. Let’s explore what goes wrong.

3.2 Error #1: object 'x' not found

⭐ BEGINNER 🔗 SCOPING

3.2.1 The Error

# Try to use an object that doesn't exist
my_number + 5
#> Error: object 'my_number' not found

🔴 ERROR

Error: object 'my_number' not found

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!

Temperature <- 98.6
temperature  # Wrong case!
#> [1] 72
# 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.3.3 Cause 3: Object Created in Different Scope

my_function <- function() {
  local_var <- 42
  print(local_var)  # Works inside function
}

my_function()
#> [1] 42
local_var  # Doesn't exist outside function!
#> Error: object 'local_var' not found

3.2.3.4 Cause 4: Cleared Environment

x <- 10
x  # Exists
#> [1] 10

rm(x)  # Removed it

# Now:
x  # Gone!
#> Error: object 'x' not found

3.2.3.5 Cause 5: Running Lines Out of Order

# If you run line 10 before line 5:

# Line 5
my_data <- read.csv("data.csv")

# Line 10 (run this first by mistake)
summary(my_data)  # Error! my_data doesn't exist yet

3.2.4 Solutions

SOLUTIONS

1. Check spelling carefully:

my_variable <- 10
my_variable + 5  # Correct spelling
#> [1] 15

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:

# Clear everything and start fresh
rm(list = ls())
# Or: Ctrl+Shift+F10 in RStudio (restart R)

🎯 Best Practices

  1. 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)
  2. Meaningful names: temperature_celsius > temp > t

  3. Avoid similar names:

# Confusing:
data1 <- ...
data2 <- ...
data_new <- ...
data_final <- ...
data_final2 <- ...

# Better:
raw_data <- ...
clean_data <- ...
analyzed_data <- ...
  1. 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.1 Cause 1: Package Not Loaded

# tidyverse not loaded
read_csv("data.csv")  # Error!

# Solution:
library(readr)
read_csv("data.csv")  # Works!

3.3.3.2 Cause 2: Package Not Installed

library(somepackage)  # If not installed, this errors
Error in library(somepackage) : 
  there is no package called 'somepackage'

3.3.3.3 Cause 3: Typo in Function Name

# Base R function is read.csv (dot), not read_csv (underscore)
meen(c(1, 2, 3))  # Typo: mean
#> Error in meen(c(1, 2, 3)): could not find function "meen"

3.3.3.4 Cause 4: Object Overwrote Function

# Created an object with same name as a function
mean <- 42
mean
#> [1] 42
# Now the function is gone!
mean(c(1, 2, 3))  
#> [1] 2

🔴 ERROR

Error in mean(c(1, 2, 3)) : could not find function "mean"

Wait, what? We just used mean! But we overwrote it with the number 42.

3.3.4 Solutions

SOLUTIONS

1. Load the required package:

library(readr)
read_csv("data.csv")

2. Install then load:

install.packages("readr")
library(readr)

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 underscore

5. 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] 2

6. Find where function lives:

# Search for functions
??read_csv
help.search("read_csv")

# Find package
find("read_csv")

⚠️ 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:

# You created: sum <- 100
sum(1:10)  # Error!

# Fix:
rm(sum)  # Remove it
sum(1:10)  # Works now

# Or restart R session: Ctrl+Shift+F10

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

my variable <- 10  # Spaces not allowed!
#> Error in parse(text = input): <text>:1:4: unexpected symbol
#> 1: my variable
#>        ^
# Solutions:
my_variable <- 10  # underscore
myVariable <- 10   # camelCase
my.variable <- 10  # dot (less recommended)

3.4.3.2 Cause 2: Missing Operator

x <- 5
y <- 10
result <- x y  # Missing operator!
#> Error in parse(text = input): <text>:3:13: unexpected symbol
#> 2: y <- 10
#> 3: result <- x y
#>                ^
# Fix:
result <- x * y  # or +, -, /, etc.
#> Error: object 'x' not found

3.4.3.3 Cause 3: Two Statements on One Line

x <- 5 y <- 10  # Two assignments without separator
#> Error in parse(text = input): <text>:1:8: unexpected symbol
#> 1: x <- 5 y
#>            ^
# Solutions:
x <- 5; y <- 10  # Semicolon separator

# Or on separate lines (preferred):
x <- 5
y <- 10

3.4.3.4 Cause 4: Incorrect String Quotes

text <- "Hello world"  # Unmatched quotes
# Fix:
text <- "Hello world"  # Matching quotes

3.4.3.5 Cause 5: Copying from Formatted Text

# Copying from Word/PDF might include smart quotes or special characters
name <- "John"  # These aren't regular quotes!
# Should be:
name <- "John"  # Regular ASCII quotes

3.4.4 Solutions

SOLUTIONS

1. Use underscores for multi-word names:

total_sales <- 1000
average_temperature <- 72.5

2. Add missing operators:

a <- 10
b <- 5
c <- a + b  # Not: c <- a b

3. Separate statements:

# One per line:
x <- 1
y <- 2

# Or use semicolon:
x <- 1; y <- 2

4. Use consistent quotes:

# Choose one style and stick to it:
text1 <- "double quotes"  # More common in R
text2 <- 'single quotes'  # Also fine

# They're equivalent:
identical(text1, "double quotes")
#> [1] TRUE
identical(text2, 'single quotes')
#> [1] TRUE

3.5 Error #4: unexpected '=' in "x"

⭐ BEGINNER 🔤 SYNTAX

3.5.1 The Error

x = 5 = y
#> Error in 5 = y: invalid (do_set) left-hand side to assignment

🔴 ERROR

Error: unexpected '=' in "x = 5 ="

3.5.2 What It Means

You used = where R didn’t expect it.

3.5.3 Common Causes

3.5.3.1 Cause 1: Chained Assignment (doesn’t work like math)

# Trying to set x and y to 5 (like math: x = y = 5)
x = 5 = y  # Doesn't work!
#> Error in 5 = y: invalid (do_set) left-hand side to assignment
# Solutions:
x <- y <- 5  # This works
# Or:
x <- 5
y <- 5

3.5.3.2 Cause 2: Using = Instead of ==

x <- 10
if (x = 10) {  # Assignment, not comparison!
  print("yes")
}
#> Error in parse(text = input): <text>:2:7: unexpected '='
#> 1: x <- 10
#> 2: if (x =
#>          ^
# Fix: use == for comparison
if (x == 10) {
  print("yes")
}

3.5.3.3 Cause 3: Wrong Context for =

# Inside function arguments, = is fine:
mean(x = c(1, 2, 3))  # OK

# For assignment, <- is clearer:
x <- c(1, 2, 3)  # Better style

3.5.4 Solutions

SOLUTIONS

1. Use <- for assignment:

# Preferred in R
x <- 10

2. Use == for comparison:

x <- 10
x == 10  # TRUE
#> [1] TRUE
x == 5   # FALSE
#> [1] FALSE

3. Use = only in function arguments:

# Good:
mean(x = c(1, 2, 3), na.rm = TRUE)
#> [1] 2

# Also fine, but <- preferred for assignment:
x <- c(1, 2, 3)
mean(x, na.rm = TRUE)
#> [1] 2

💡 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

data <- c(1, 2, 3, 4, 5)
result <- mean  # Forgot parentheses!
result[1]  # Trying to subset the function itself
#> Error in result[1]: object of type 'closure' is not subsettable
# Fix:
result <- mean(data)  # Call the function
result  # Now it's a number
#> [1] 3

3.6.3.2 Cause 2: Accidentally Accessed Function Instead of Object

# You have an object named 'data'
data <- data.frame(x = 1:5, y = 6:10)

# But there's also a function called 'data'
data[1, ]  # If you somehow reference the function...
#>   x y
#> 1 1 6

This is rare, but shows why naming is important.

3.6.3.3 Cause 3: Function Name Typo Leads to Another Function

c <- c(1, 2, 3)  # Bad! 'c' is a function
c[1]  # Now trying to subset the c() function
#> [1] 1

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] 2

2. Check if it’s a function:

is.function(mean)  # TRUE
#> [1] TRUE
is.function(c(1,2,3))  # FALSE
#> [1] FALSE

3. Don’t overwrite function names:

# Bad:
c <- c(1, 2, 3)
t <- read.csv("data.csv")
data <- process_data()

# Good:
my_vector <- c(1, 2, 3)
my_data <- read.csv("data.csv")
processed_data <- process_data()

3.7 Error #6: cannot change value of locked binding

⭐⭐ INTERMEDIATE 🔗 SCOPING

3.7.1 The Error

T <- FALSE  # Trying to change T

🔴 ERROR

Error in T <- FALSE : cannot change value of locked binding for 'T'

3.7.2 What It Means

You’re trying to modify a protected object. Some objects are locked to prevent accidental changes.

3.7.3 Common Protected Objects

# These are locked:
T  # TRUE
F  # FALSE
pi
letters
LETTERS
month.name
month.abb

3.7.4 Why This Protection Exists

# Imagine if you could do this:
T <- FALSE
F <- TRUE

# Now:
if (T) {  # But T is FALSE!
  print("This won't print")
}

# Chaos!

3.7.5 Solutions

SOLUTIONS

1. Use a different name:

# Don't:
# T <- FALSE

# Do:
my_test <- FALSE
temperature <- 72

2. Use full names (better practice anyway):

# Instead of T/F:
my_var <- TRUE   # Not T
other_var <- FALSE  # Not F

# More readable and no risk of confusion

3. Never use T/F in code:

# Bad:
if (x > 0) T else F
#> Error in if (x > 0) T else F: the condition has length > 1

# Good:
if (x > 0) TRUE else FALSE
#> Error in if (x > 0) TRUE else FALSE: the condition has length > 1

⚠️ Common Pitfall: T and F

Never use T and F as shortcuts for TRUE and FALSE

Why? - They can be overwritten (in older R) - Less readable - Can cause subtle bugs

# Dangerous:
result <- T  # What if someone changed T?

# Safe:
result <- TRUE  # Can never be changed

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 y
print(y)  # Error!
#> [1] 5

Scoping 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  # ERROR

Reserved 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:

# Snake case (recommended for R)
total_sales <- 1000
avg_temperature <- 72
customer_age <- 35

# CamelCase (also fine)
totalSales <- 1000
avgTemperature <- 72
customerAge <- 35

# Whatever you choose, be consistent!

3.10 Summary

Key Takeaways:

  1. R is case-sensitive: Xx
  2. Check spelling: Most “object not found” errors are typos
  3. Load packages: Functions need library() or ::
  4. Don’t overwrite functions: Avoid naming objects after functions
  5. Use <- for assignment: Clearer than =
  6. No spaces in names: Use _ or camelCase
  7. Check environment: Use ls() and RStudio’s Environment pane
  8. 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?

# 1
my result <- 100

# 2
Mean <- mean(c(1, 2, 3))
meen(c(4, 5, 6))

# 3
x = 10
if (x = 10) print("yes")

# 4
c <- c(1, 2, 3)
c[1]

# 5
library(dplyr)
select(data, column1)  # data doesn't exist

# 6
T <- FALSE

📝 Exercise 2: Debug This Script

Fix all errors:

# Load data
my data <- read.csv("results.csv")

# Calculate mean
average <- Mean(my data$value)

# Compare
if (average = 50) {
  print("Average is 50")
}

# Store result
T <- average > 50

📝 Exercise 3: Good Names

Rename these variables following best practices:

# Current (bad) names:
x <- data.frame(...)
data <- read.csv("sales.csv")
t <- TRUE
result1 <- ...
result2 <- ...
finaldata <- ...

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 name

Exercise 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 T

Exercise 3:

# Better names:
sales_dataframe <- data.frame(...)  # or just sales_data
sales_data <- read.csv("sales.csv")
is_valid <- TRUE  # or use full TRUE
raw_results <- ...
clean_results <- ...
final_sales_data <- ...  # or analyzed_sales