R Advanced
Summary Table
Summary of the R Advanced section.
Concept | Example | Description |
---|---|---|
Basic function | greet <- function() { print("Hi") } |
Define a reusable block of code |
Parameters | function(name) { print(name) } |
Accept input values into the function |
Return values | return(x + y) |
Send a result back to the caller |
Default values | function(name = "Guest") |
Provide fallback values for parameters |
Named arguments | fun(b = 2, a = 1) |
Pass arguments by name in any order |
Variable arguments | function(...) |
Accept any number of inputs |
Access ... |
args <- list(...) |
Convert ... to a list of named arguments |
Multiple return values | return(list(sum = x + y, diff = x - y)) |
Return a list to simulate multiple return values |
Missing required argument | fun(x) → fun() |
Error if required arg isn’t provided |
Missing parentheses | function(x (syntax error) |
Missing closing ) breaks the function |
Load a package | library(ggplot2) |
Make all functions in a package available |
Conditional loading | if (require(pkg)) { ... } |
Load only if available; returns TRUE/FALSE |
Aliased access | dplyr::filter() |
Use function without loading full package |
Load custom script | source("utils.R") |
Run code from another R file |
Access dataset | data(mtcars) |
Load built-in dataset |
View top rows | head(mtcars) |
Show first 6 rows |
Summary stats | summary(df) |
Get mean, median, min, max, etc. |
Handle NA | na.omit(df) |
Remove missing data |
Impute mean | df$var[is.na(var)] <- mean(var, na.rm=TRUE) |
Replace NAs with average |
Normalize | (x - min(x)) / (max(x) - min(x)) |
Rescale between 0 and 1 |
Scale (standardize) | scale(df) |
Mean = 0, SD = 1 |
Scatter plot | ggplot(df, aes(x, y)) + geom_point() |
Basic scatterplot using ggplot2 |
Histogram | geom_histogram(binwidth = 2) |
Show frequency distribution |
Import error | library(badpkg) |
Error if package doesn’t exist |
Function not loaded | select(df) without library(dplyr) |
Error if function isn’t available in namespace |