1.3. Writing Code
1.3.5 Most Useful Miscellaneous Operators in R
| Operator | Purpose | Example | Description |
|---|---|---|---|
: |
Create a sequence of integers | 1:5 → 1 2 3 4 5 |
Generates a range of numbers in order. Useful for loops, indexing, and quick vector creation. |
%in% |
Test membership in a set | x %in% c("A", "B") |
Checks if each element of x appears in the given vector. Returns a logical vector (TRUE/FALSE) for each element. |
:: |
Use function from a specific package | dplyr::filter() |
Ensures the function is called from a specified package, avoiding conflicts when multiple packages have functions with the same name. |
$ |
Access column or list element | df$AVAL |
Retrieves a named element (commonly a column in a data frame or a named item in a list). Convenient for interactive work and readable code. |
[[ |
Extract by name or index | list[["val"]] or list[[1]] |
Used for extracting elements from lists or data frames by name or position. Allows dynamic referencing and is more flexible than $. |
Sequence Operator (
:):- Quickly creates a sequence of consecutive integers.
- Commonly used in loops, indexing, and generating ranges.
- Example:
index <- 1:5 # index is: 1 2 3 4 5 for (i in 1:3) print(i) # Prints 1, 2, 3
Membership Operator (
%in%):- Checks if elements of a vector exist in another vector.
- Returns a logical vector of the same length as the left operand.
- Example:
x <- c("A", "B", "C") x %in% c("A", "C") # [1] TRUE FALSE TRUE - Useful for filtering data frames:
labs$flag <- labs$PARAM %in% c("SYSBP", "PULSE") # labs$flag is TRUE for rows where PARAM is "SYSBP" or "PULSE"
Namespace Operator (
::):- Calls a function from a specific package, even if it is not loaded with
library(). - Prevents ambiguity if multiple packages have functions with the same name.
- Example:
dplyr::filter(labs, AVAL > 100) # Uses filter from dplyr, not from another package
- Calls a function from a specific package, even if it is not loaded with
Dollar Sign Operator (
$):- Accesses columns in a data frame or named elements in a list.
- Example:
labs$AVAL # Accesses the AVAL column in labs data frame mylist$name # Accesses the 'name' element in a list - Only works with valid R names (no spaces or special characters).
Double Bracket Operator (
[[):- Extracts elements from lists or data frames by name or index.
- More flexible than
$because it allows dynamic referencing. - Example:
list_data <- list(value = 42, other = 99) list_data[["value"]] # Returns 42 list_data[[1]] # Also returns 42 (first element) colname <- "value" list_data[[colname]] # Dynamic extraction - Also used for extracting single columns from data frames:
df[["AVAL"]]
**Resource download links**
1.3.5.-Most-Useful-Miscellaneous-Operators-in-R.zip
⁂