COURSE ยท 8 LESSONS ยท 100% FREE
๐Ÿ“Š

R Programming

The language of statisticians and data scientists. Data analysis, visualization, and machine learning.

0Lessons
0Code Examples
ZeroPrerequisites
0%
You've completed 0 of 8 lessons
J/โ†“ Next
K/โ†‘ Prev
Esc Collapse
/ Search
Foundations
01

Hello World & Setup

print() for output. <- for assignment. Everything is a vector.

๐Ÿง  Note for the confused:
Rust is like that friend who's REALLY strict about safety. 'You want to modify this variable? Sign this permission slip first.' That's called mutability. Rust doesn't let you touch anything without asking.
print("Hello, World!")
name <- "Mayank"
age <- 15
cat(name, "is", age, "\n")

# Assignment
x <- 42
y = 10
print(x + y)

# Run: Rscript file.R
# Or: R -f file.R
02

Vectors & Types

c() creates vectors. Numeric, character, logical. Vectorized operations.

๐Ÿง  Note for the confused:
Data types in Rust are like a very specific coffee order. 'I'd like a u32 with extra bits, hold the overflow.' Rust knows exactly how many bits everything is. No surprises. Except when the compiler yells at you.
# Vectors
nums <- c(1, 2, 3, 4, 5)
langs <- c('Python', 'R', 'Go')
flags <- c(TRUE, FALSE, TRUE)

# Types
print(typeof(nums))    # double
print(class(nums))     # numeric
print(is.numeric(nums))# TRUE

# Vectorized ops
print(nums * 2)        # 2 4 6 8 10
print(nums + nums)     # 2 4 6 8 10
print(nums > 3)        # FALSE FALSE FALSE TRUE TRUE

# Useful functions
print(length(nums))    # 5
print(sum(nums))       # 15
print(mean(nums))      # 3
print(sort(nums, decreasing=TRUE))
print(seq(1, 10, by=2))  # 1 3 5 7 9
print(rep('hi', 3))     # hi hi hi
03

Lists & Data Frames

Lists hold anything. Data frames are tables. data.frame() is your spreadsheet.

๐Ÿง  Note for the confused:
Functions in Rust look like every other language, but then Rust adds '->' for return types like it's pointing dramatically at what you'll get back. 'Behold! This function returns AN INT!'
# Lists
person <- list(name='Mayank', age=15, langs=c('R', 'Python'))
print(person$name)
print(person[['age']])

# Data frames
df <- data.frame(
  name = c('Alice', 'Bob', 'Charlie'),
  age = c(20, 12, 25),
  score = c(95, 88, 72)
)
print(df)
print(df$name)
print(df$age)

# Subset
print(df[df$age > 18, ])
print(df[df$score > 80, 'name'])

# Summary
summary(df)
str(df)

# Add column
df$grade <- ifelse(df$score >= 90, 'A', ifelse(df$score >= 80, 'B', 'C'))
print(df)
04

Control Flow & Functions

if/else, for, while, function(). Vectorized ifelse() for vectors.

๐Ÿง  Note for the confused:
Ownership in Rust is like library books. One person borrows the book (ownership). When they're done, the book goes back. You can READ the book (borrow) without taking it home. Try to keep two copies and the librarian (compiler) screams.
score <- 85
if (score >= 90) print('A')
else if (score >= 80) print('B')
else print('C')

# Vectorized ifelse
scores <- c(95, 72, 88, 60)
grades <- ifelse(scores >= 90, 'A', ifelse(scores >= 80, 'B', ifelse(scores >= 70, 'C', 'F')))
print(grades)

# For loop
for (i in 1:5) print(i)

# Functions
add <- function(a, b) a + b
factorial <- function(n) if (n <= 1) 1 else n * factorial(n - 1)
circle_area <- function(r) pi * r^2

print(add(3, 4))
print(factorial(5))
print(circle_area(5))

# Apply family
nums <- list(c(1,2,3), c(4,5,6), c(7,8,9))
print(lapply(nums, sum))
print(sapply(nums, mean))
Data Science
05

Data Import & Cleaning

read.csv, read_excel, dplyr for filtering, selecting, mutating.

๐Ÿง  Note for the confused:
Structs in Rust are like forms you fill out at the DMV. You define the fields (name, age, etc.), fill them in, and boom - you have a person struct. Way less waiting in line. No horrible fluorescent lighting.
library(dplyr)

# Read CSV
df <- read.csv('data.csv')

# dplyr operations
result <- df %>%
  filter(age > 18) %>%
  select(name, score) %>%
  mutate(grade = ifelse(score >= 90, 'A', 'B')) %>%
  arrange(desc(score))

# Handle missing values
df_clean <- na.omit(df)
df_filled <- df %>% mutate(score = ifelse(is.na(score), mean(score, na.rm=TRUE), score))

# Group by
df_summary <- df %>%
  group_by(grade) %>%
  summarise(count = n(), avg_score = mean(score))

print(result)
print(df_summary)
06

Visualization (ggplot2)

Grammar of graphics. aes() for aesthetics, geom_ for chart types. Layer by layer.

๐Ÿง  Note for the confused:
Enums in Rust are like a multiple choice question where every answer could be a completely different thing. 'Is this variable a Number, a Text, or a Black Hole?' Rust says 'yes'.
library(ggplot2)

# Scatter plot
ggplot(data, aes(x=age, y=score, color=grade)) +
  geom_point(size=3) +
  geom_smooth(method='lm') +
  labs(title='Score vs Age', x='Age', y='Score') +
  theme_minimal()

# Bar chart
ggplot(data, aes(x=grade, fill=grade)) +
  geom_bar() +
  scale_fill_manual(values=c('A'='green', 'B'='blue', 'C'='orange'))

# Histogram
ggplot(data, aes(x=score)) +
  geom_histogram(binwidth=5, fill='steelblue', alpha=0.7)

# Box plot
ggplot(data, aes(x=grade, y=score, fill=grade)) +
  geom_boxplot() +
  theme_minimal()
07

Statistical Testing

t-test, chi-square, ANOVA, correlation. R was built for statistics.

library(dplyr)

# T-test
t_test_result <- t.test(score ~ group, data=df)
print(t_test_result)

# Correlation
cor_matrix <- cor(df %>% select(age, score, hours))
print(cor_matrix)

# Chi-squared test
chi <- chisq.test(table(df$grade, df$gender))
print(chi)

# Linear regression
model <- lm(score ~ age + hours, data=df)
summary(model)

# Predict
new_data <- data.frame(age=20, hours=5)
predict(model, newdata=new_data)

# ANOVA
anova_result <- aov(score ~ group, data=df)
summary(anova_result)
08

R Markdown & Shiny

Reproducible reports with R Markdown. Interactive web apps with Shiny.

# R Markdown (.Rmd)
# ---
# title: "My Report"
# output: html_document
# ---
# ```{r}
# library(ggplot2)
# ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
# ```

# Shiny app
library(shiny)

ui <- fluidPage(
  titlePanel("Score Dashboard"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("n", "Number:", min=1, max=100, value=50)
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

server <- function(input, output) {
  output$plot <- renderPlot({
    hist(rnorm(input$n), col='steelblue', main='Histogram')
  })
}

shinyApp(ui, server)