[![](https://img.shields.io/badge/download%20html-blue)](../rendered-html/objects-variables.html)
[![](https://img.shields.io/badge/download%20Rmd-blue)](objects-variables.Rmd)

```{r setup, include=FALSE}
# Set global options for all code chunks
knitr::opts_chunk$set(echo = TRUE)  # Display code in output
```

## Introduction

In R, we work with objects to store and manipulate data. Understanding how to create and work with objects is fundamental to using R effectively. This lesson will cover the basics of working with objects and variables in R, using examples relevant to medical and health sciences, including RNA sequencing analysis.

## Creating Objects

```{r basic-objects}
# Store a gene expression value as a numeric object
# Typical RNA-seq count data might be in this range
expression_level <- 1543.7           # Numeric value representing expression

# Store a gene name as a character (text) object
gene_name <- "BRCA1"                # String value for breast cancer gene 1

# Store a boolean flag for differential expression
is_differentially_expressed <- TRUE  # Logical value (TRUE/FALSE)

# Display all our created objects with labels
print("Expression level:")           # Print label
print(expression_level)             # Print numeric value
print("Gene name:")                 # Print label
print(gene_name)                    # Print string value
print("Is differentially expressed?") # Print label
print(is_differentially_expressed)   # Print logical value
```

### Pro Tip
In RStudio, you can type `Alt + -` (Windows/Linux) or `Option + -` (Mac) to create the assignment operator `<-` in one keystroke!

## Naming Conventions

When naming objects in R, follow these guidelines:

✅ **Good Names:**
- Use descriptive names: `read_count`, `expression_level`
- Start with letters: `gene_1`, `sample_id`
- Use underscores for spaces: `fold_change`

❌ **Avoid:**
- Starting with numbers: `2nd_replicate` (invalid)
- Using spaces: `gene expression` (invalid)
- Using special characters: `gene@1` (invalid)
- Using R reserved words: `if`, `else`, `function`

## Working with Objects

```{r calculations}
# RNA-seq example: Calculate fold change between treated and control samples
control_expression <- 100           # Control sample expression level
treated_expression <- 200          # Treated sample expression level
fold_change <- treated_expression / control_expression  # Calculate ratio
print("Fold change:")              # Print label
print(fold_change)                 # Will show 2x increase

# Medical example: Calculate Body Mass Index (BMI)
weight_kg <- 70.5                  # Patient weight in kilograms
height_m <- 1.75                   # Patient height in meters
bmi <- weight_kg / (height_m^2)    # BMI formula: weight/(height^2)
print("BMI calculation:")          # Print label
print(bmi)                         # Will show BMI value
```

## Practice Challenges

### Challenge 1: Basic Calculations
```{r challenge1}
# Initialize read count from sequencing data
read_count <- 1000                 # Initial number of reads
scaling_factor <- 1.5              # Factor to adjust for library size
read_count <- read_count * scaling_factor  # Apply scaling
normalized_count <- read_count / 10  # Further normalization step

# Display results of calculations
print("Final read count:")         # Show scaled count
print(read_count)
print("Normalized count:")         # Show normalized value
print(normalized_count)
```

### Challenge 2: Temperature Conversion
```{r challenge2}
# Convert patient temperature from Celsius to Fahrenheit
temp_celsius <- 37.5              # Normal body temperature in Celsius
# Formula: (°C × 9/5) + 32
temp_fahrenheit <- (temp_celsius * 9/5) + 32  # Convert to Fahrenheit

# Display the conversion result with units
print("Temperature conversion:")
print(paste(temp_celsius, "°C =", temp_fahrenheit, "°F"))
```

### Challenge 3: Sample Information
```{r challenge3}
# Create variables for sample metadata
sample_id <- "RNA_01"             # Unique sample identifier
gene_name <- "TP53"              # Target gene (tumor protein p53)
expression_value <- 2456         # Expression count for this gene

# Combine information into a readable message using paste()
message <- paste("Sample", sample_id, "shows", expression_value, 
                "counts for gene", gene_name)
print("Combined message:")        # Print formatted message
print(message)
```

## Common Mistakes and How to Avoid Them

1. **Case Sensitivity Demonstration**
```{r case-sensitivity}
# R is case-sensitive - these are three different variables
expression <- 5000               # lowercase
Expression <- 6000               # Title case
EXPRESSION <- 7000              # uppercase

# Show how all three variables are distinct
print("Three different variables:")
print(expression)               # Shows 5000
print(Expression)              # Shows 6000
print(EXPRESSION)              # Shows 7000
```

2. **Object Overwriting Example**
```{r overwriting}
# Initial value assignment
read_depth <- 1000000          # One million reads
print("Original read depth:")
print(read_depth)

# Overwriting with new value
read_depth <- 1500000          # Changed to 1.5 million reads
print("New read depth:")
print(read_depth)              # Original value is lost
```

3. **Invalid Names Example**
```{r invalid-names, eval=FALSE}
# Examples of invalid variable names (these will cause errors)
1st_sample <- 5               # Invalid: starts with number
sample name <- "Control"      # Invalid: contains space
```

## Tips for Success

1. Always use clear, descriptive names for your objects
2. Be consistent with your naming style (e.g., `gene_name`, `sample_id`)
3. Check your objects exist by typing their name
4. Use the `ls()` function to see all objects in your environment
5. Use `rm(object_name)` to remove objects you no longer need

```{r tips}
# Display all objects in current environment
print("Objects in environment:")
ls()                          # List all variables

# Remove a specific object from environment
rm(expression)               # Delete 'expression' variable
print("Objects after removing 'expression':")
ls()                         # Show updated list
```

## Next Steps

After mastering basic objects and variables, you can move on to:
- Working with data vectors and matrices
- Understanding data types and structures
- Learning how to create and use functions
- Working with data frames 