Server Info & Course Info
print("Hello World")
2 + 3
sqrt(25)
↑/↓ Arrow keys: Cycle through command historyTab: Auto-complete for:
Ctrl + C: Interrupt current commandCtrl + L: Clear console screenR.version.string
getwd()
installed.packages()
nano first_program.R# My First R Script
message <- "Welcome to Data Analysis!"
print(message)
Ctrl+O → Enter → Ctrl+XRscript first_program.Rlowercase_with_underscoresv01_initial_script.Rv02_updated_script.R# Data Cleaning Section ------------------------
# Calculates Euclidean distance between two points
# Input: Numeric vectors x and y
# Output: Scalar distance value
# TODO: Implement error handling here
# TEST: Verify input dimensions
print(dim(data_matrix))
| Error Type | Examples | Quick Checks |
|---|---|---|
| Syntax Errors | Missing ), } |
Color highlighting in editor |
| Runtime Errors | object 'var' not found |
ls() to list variables |
| Logical Errors | Incorrect algorithm implementation | Add print() statements |
| Package Errors | there is no package called... |
Verify installation with install.packages() |
sessionInfo())cdls -l script.R# Valid names
my_var <- 5
Var2 <- "text"
.height <- 7.2 # Hidden variable
# Invalid names
2var <- 10 # Error: Starts with number
if <- 20 # Error: Reserved word
Key Rules:
myVar ≠ myvarif, function, NULL). and _)my_variable)x <- 5 # Recommended style
y = 10 # Works but less common
25 -> z # Right assignment (rare)
# Scope differences in functions:
median(x = 1:10) # Temporary assignment
median(x <- 1:10) # Creates permanent object
Community Preference:
<- for object creation= for function arguments# List objects
ls() # All variables
ls(pattern = "^x") # Filter by pattern
# Remove variables
rm(x) # Remove single
rm(list = ls()) # Clear environment
# Environment comparison
.GlobalEnv # Default workspace
search() # Attached packages
# Default is double
num1 <- 15 # Type: double
num2 <- 15L # Explicit integer
# Type checking
typeof(num1) # "double"
is.integer(num2) # TRUE
# Scientific notation
1.2e3 == 1200 # TRUE
# Quote variations
str1 <- "Hello's World" # Double quotes
str2 <- 'He said "Hi"' # Single quotes
# Escape characters
path <- "C:\\Documents\\file.txt"
cat(path) # C:\Documents\file.txt
# Concatenation
paste("RNA", "seq", sep = "-") # "RNA-seq"
# Basic logic
is_valid <- TRUE
is_empty <- FALSE
# Quick input
T <- FALSE # Dangerous! (T is redefined)
TRUE <- 5 # Error: Reserved word
# Best practice: Always spell out
valid <- TRUE
# Explicit conversion
as.numeric("123") # 123
as.character(45.7) # "45.7"
as.integer(TRUE) # 1
# Automatic conversion
sum(c(TRUE, FALSE)) # 1 (logical → numeric)
"Value:" + 5 # Error (implicit failure)
Watch for:
as.numeric("ABC") # NA with warning
# Detection
x <- c(1, NA, 3)
is.na(x) # FALSE TRUE FALSE
# Operations
sum(x) # NA
sum(x, na.rm=TRUE) # 4
# Special cases
NA == NA # NA (not TRUE)
# NULL (empty object)
length(NULL) # 0
x <- NULL
# NaN (Not a Number)
0/0 # NaN
sqrt(-1) # NaN with warning
# Inf/-Inf
1/0 # Inf
log(0) # -Inf
Checking Methods:
is.null(x) # For NULL
is.nan(y) # For NaN
is.infinite(z) # For Inf/-Inf
%%# Check divisibility
9 %% 3 # Returns 0
7 %% 2 # Returns 1
# Practical application: Batch processing
i=1
while(i<=10000){
if(i %% 100 == 0){
print(paste("Processing batch", i/10000))
}
Sys.sleep(0.001)
i=i+1
}
2^3 # 8
2**3 # 8 (equivalent)
^ for better code readability in R0.1 + 0.2 == 0.3 # FALSE
all.equal(0.1+0.2, 0.3) # TRUE
== with floating numbersc(1,3,5) > 2 # Returns FALSE TRUE TRUE
# & (vectorized)
c(TRUE, FALSE) & c(FALSE, FALSE) # FALSE FALSE
# && (single-element)
c(TRUE, FALSE) && c(FALSE, FALSE) # FALSE
x <- 5
x > 3 & x < 10
x > 3 && x < 10
x <- c(5,7)
x > 3 & x < 10
x > 3 && x < 10
# || stops at first TRUE
ppp = function(){
print('ok')
return(FALSE)}
TRUE || ppp()
FALSE || ppp()
() - Parentheses^ - Exponentiation%% - Modulus* / - Multiplication/Division+ - - Addition/Subtraction> < - Comparisons! - NOT& && - AND| || - OR<- - Assignment3 + 5 * 2 ^ 2 # = 3 + (5*(2^2)) = 23
x <- 5 + (a & b)&/| over &&/|| unless specifically neededall.equal() instead of == for numeric comparisons# paste() with separator
paste("Hello", "World", sep = " ") # "Hello World"
# paste0() for direct concatenation
paste0("File_", 1:3, ".txt") # "File_1.txt" "File_2.txt" "File_3.txt"
**Key Difference:**
- `paste()`: Default space separator, customizable
- `paste0()`: No separator (equivalent to paste(..., sep=""))
# Basic splitting
result <- strsplit("apple,orange,banana", ",")
# Returns list: [[1]] [1] "apple" "orange" "banana"
# Accessing elements
result[[1]][2] # "orange"
**Important Characteristics:**
- Always returns a *list* structure
- Use `unlist()` to convert to vector:
unlist(strsplit("a-b-c", "-")) # [1] "a" "b" "c"
# Find matching elements
colors <- c("red", "blue", "green2", "yellow3")
grep("\\d", colors) # Returns positions: 3 4
# Get actual values
grep("\\d", colors, value=TRUE) # "green2" "yellow3"
**Common Flags:**
- `ignore.case=TRUE`: Case-insensitive matching
- `invert=TRUE`: Return non-matching elements
| Character | Meaning | Example |
|---|---|---|
^ |
Start of string | ^A matches “Apple” not “aPple” |
$ |
End of string | d$ matches “end” not “ending” |
. |
Any single character | a.c matches “abc”, “a2c” |
* |
Zero or more repeats | lo* matches “l”, “lo”, “loo” |
Example:
grep("^[A-Z]", c("Apple", "banana")) # 1 (matches first element)
# Good practice
long_text <- "This is a multi-line
string in R. Use explicit newline
characters for clarity."
# Problematic approach
bad_text <- "This might cause
unexpected indentation"
# Common escape sequences
cat("Line1\nLine2") # New line
cat("Column1\tColumn2") # Tab
cat("C:\\Program Files\\R") # Backslash
**Essential Escapes:**
- `\n`: New line
- `\t`: Tab
- `\\`: Literal backslash
- `\"`: Literal double quote
# Handling NA values
nchar(NA) # Returns NA
nchar("NA") # Returns 2
# Safe approach
nchar(na.omit(c("text", NA))) # Length: 4
**Best Practice:**
- Always pre-process NA values before using nchar()
- Consider `stringi::stri_length()` for alternative NA handling
# Proper nested formatting example
a=5
if (a<1) {
print('less than 1')
} else if (a<4) {
print('a>=1 and a<4')
} else {
print('a>=4')
}
Key Points:
{} even for single-line statementsx=c(5,7)
# Traditional approach
result <- vector()
for (i in 1:length(x)) {
result[i] <- if (x[i] > 0) "Positive" else "Negative"
}
# Vectorized approach
result <- ifelse(x > 0, "Positive", "Negative")
Advantages:
# Basic syntax
operation <- function(op, x, y) {
switch(op,
"add" = x + y,
"sub" = x - y,
"mul" = x * y,
stop("Invalid operation"))
}
Use Cases:
# Index styles comparison
for (i in 1:5) {...} # Basic numeric range
for (i in seq_along(vec)) {...} # Safer for empty vectors
for (item in vector) {...} # Direct element access
Protection Tips:
length(vector) > 0 before loopingseq_along() instead of 1:length() to handle empty vectorspurrr::map() for functional programming# Safe while template
counter <- 0
while (condition && counter < max_iter) {
# loop body
counter <- counter + 1
}
Essential Checks:
max_iter = 1e6)for (i in 1:10) {
if (i %% 2 == 0) next # Skip even numbers
if (i > 7) break # Early exit
print(i)
}
When to Use:
next: Skip invalid/irrelevant casesbreak: Error conditions met, or early completion# Before loop
if (length(data) == 0) {
stop("Empty input dataset")
}
# In while loops
timeout <- Sys.time() + 300 # 5-minute timeout
while (condition) {
if (Sys.time() > timeout) {
stop("Execution timeout reached")
}
# ...
}
# Loop approach
total <- 0
for (num in numbers) {
total <- total + num
}
# Vectorized approach
total <- sum(numbers)
# Benchmark comparison (1M elements):
- Loop: 0.15s
- Vectorized: 0.0001s
Key Functions:
# Poor practice
result <- c()
for (i in 1:1e5) {
result <- c(result, i^2)
}
# Proper pre-allocation
result <- numeric(1e5)
for (i in 1:1e5) {
result[i] <- i^2
}
Performance Gain:
# AI-Assisted Exercise
"Ask ChatGPT/Kimi to help write a function that:
1. Takes numeric vector input
2. Uses ifelse() to replace negative values with NA
3. Calculates mean with vectorized operations
4. Includes defensive programming checks"
When Stuck:
Example Prompt:
“Help me convert this for-loop to while-loop:
for (i in 1:length(x)) {
print(i)
}”