Variables & Data Types
7 snippetsVariable
name <- "John" Numeric
age <- 25 Vector
nums <- c(1, 2, 3, 4, 5) List
person <- list(name = "John", age = 30) Matrix
mat <- matrix(1:9, nrow = 3, ncol = 3) Data Frame
df <- data.frame(name = c("A", "B"), age = c(25, 30)) Factor
status <- factor(c("low", "high", "medium")) Control Flow
5 snippetsIf/Else
if (x > 0) {
print("positive")
} else if (x < 0) {
print("negative")
} else {
print("zero")
} For Loop
for (i in 1:5) {
print(i)
} While Loop
while (count < 10) {
count <- count + 1
} Apply
sapply(1:5, function(x) x^2) Ifelse
result <- ifelse(x > 0, "positive", "non-positive") Functions
4 snippetsFunction
greet <- function(name) {
paste("Hello,", name, "!")
} Default Args
greet <- function(name = "World") {
paste("Hello,", name, "!")
} Return
add <- function(a, b) {
return(a + b)
} Anonymous
function(x) x^2 Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Vector Operations
6 snippetsCreate
v <- c(1, 2, 3, 4, 5) Sequence
seq(1, 10, by = 2) # 1, 3, 5, 7, 9 Repeat
rep(1, 5) # 1, 1, 1, 1, 1 Index
v[1] # First element
v[2:4] # Elements 2 to 4 Filter
v[v > 2] # Elements greater than 2 Operations
sum(v)
mean(v)
max(v)
length(v) Data Frames
6 snippetsCreate
df <- data.frame(
name = c("Alice", "Bob"),
age = c(25, 30)
) Access Column
df$name
df[["name"]]
df[, "name"] Access Row
df[1, ] # First row Filter
df[df$age > 25, ] Add Column
df$city <- c("NYC", "LA") Merge
merge(df1, df2, by = "id") Packages
6 snippetsInstall
install.packages("dplyr") Load
library(dplyr) dplyr Filter
df %>% filter(age > 25) dplyr Select
df %>% select(name, age) dplyr Mutate
df %>% mutate(age_plus = age + 1) dplyr Group
df %>% group_by(city) %>% summarise(avg = mean(age))