Base R Cheat Sheet

Here’s a cheat sheet for common operations in base R:

Data Structures

Vectors:

vector <- c(1, 2, 3, 4)

Matrices:

matrix_data <- matrix(1:6, nrow = 2, ncol = 3)

Lists:

list_data <- list(1, "a", TRUE)

Data Frames:

df <- data.frame(Name = c("Zach", "Arun", "Charles"), Age = c(25, 30, 22))

Basic Operations

Arithmetic Operations:

result <- 2 + 3 * 4 / 2

Logical Operations:

logical_result <- TRUE & FALSE | TRUE

Data Manipulation

Indexing Elements:

element <- vector[2]

Subset Data Frame:

subset_df <- df[df$Age > 25, ]

Sorting Data Frame:

sorted_df <- df[order(df$Age), ]

Merge Data Frames:

merged_df <- merge(df1, df2, by = "ID", all = TRUE)

Control Structures

if-else Statement:

if (condition) {
  # code block
} else {
  # code block
}

for Loop:

for (i in 1:5) {
  # code block
}

while Loop:

while (condition) {
  # code block
}

Functions

Function Definition:

my_function <- function(arg1, arg2) {
  # code block
  return(result)
}

Apply Functions:

result <- lapply(list_data, my_function)

Data Analysis

Descriptive Statistics:

mean_value <- mean(vector)

Correlation:

correlation <- cor(df$Age, df$Height)

Linear Regression:

lm_model <- lm(Y ~ X1 + X2, data = df)

File I/O

Read CSV File:

data <- read.csv("file.csv")

Write CSV File:

write.csv(df, "output.csv", row.names = FALSE)

Plotting

Scatter Plot:

plot(df$X, df$Y, main = "Scatter Plot", xlab = "X-axis", ylab = "Y-axis")

Histogram:

hist(vector, main = "Histogram", xlab = "Values", col = "lightblue")

Miscellaneous

Help Documentation:

?function_name

Install and Load Packages:

install.packages("package_name")
library(package_name)

This cheat sheet provides a quick reference for common operations in base R. Keep in mind that R has a rich ecosystem of packages, and using specialized packages can enhance your capabilities in data analysis, visualization, and statistical modeling. For more detailed information, refer to the official R documentation.