The language of statisticians and data scientists. Data analysis, visualization, and machine learning.
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
# 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
Lists hold anything. Data frames are tables. data.frame() is your spreadsheet.
# 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)
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))
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)
Grammar of graphics. aes() for aesthetics, geom_ for chart types. Layer by layer.
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()
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)
# 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)