| name | r-expert |
| version | 1.0.0 |
| description | Expert-level R statistical computing, data analysis, and visualization |
| category | languages |
| tags | ["r","statistics","data-analysis","ggplot2","tidyverse"] |
| allowed-tools | ["Read","Write","Edit","Bash(R:*, Rscript:*)"] |
R Statistical Computing Expert
Expert guidance for R programming, statistical analysis, data visualization, and data science.
Core Concepts
R Fundamentals
- Vectors and data frames
- Factors and lists
- Functions and apply family
- Packages and libraries
- R Markdown
- Tidyverse ecosystem
Statistical Analysis
- Descriptive statistics
- Hypothesis testing
- Regression analysis
- ANOVA
- Time series analysis
- Machine learning
Data Visualization
- ggplot2
- Base R graphics
- Interactive plots (plotly)
- Statistical charts
- Maps and spatial data
R Basics
numbers <- c(1, 2, 3, 4, 5)
names <- c("Alice", "Bob", "Charlie")
df <- data.frame(
id = 1:5,
name = c("Alice", "Bob", "Charlie", "David", "Eve"),
age = c(25, 30, 35, 28, 32),
salary =
dfdfage
df
calculate_mean x
x x
sapplydfage x x
lapply
meandfage
print
print
i nrowdf
printdfnamei
Tidyverse
library(dplyr)
library(tidyr)
library(stringr)
df %>%
filter(age > 28) %>%
select(name, age, salary) %>%
mutate(
salary_bonus = salary * 1.1,
age_group = case_when(
age < 30 ~ "Young",
age < 35 ~ "Mid-career",
TRUE ~ "Senior"
)
) %>%
arrange(desc(salary)) %>%
group_by(age_group) %>%
summarise(
count = n(),
avg_salary = meansalary
total_salary salary
wide_data data.frame
id
year_2021
year_2022
long_data wide_data
pivot_longer
cols starts_with
names_to
values_to
names_prefix
wide_again long_data
pivot_wider
names_from year
values_from value
names_prefix
df
mutate
name_upper str_to_uppername
name_length str_lengthname
first_letter str_subname
df1 data.frameid value1
df2 data.frameid value2
inner_joindf1 df2 by
left_joindf1 df2 by
full_joindf1 df2 by
ggplot2 Visualization
library(ggplot2)
ggplot(df, aes(x = age, y = salary)) +
geom_point(size = 3, color = "blue") +
geom_smooth(method = "lm", se = TRUE) +
labs(
title = "Age vs Salary",
x = "Age (years)",
y = "Salary ($)"
) +
theme_minimal()
ggplot(df, aes(x = name, y = salary, fill = age_group)) +
geom_col() +
facet_wrap age_group
themeaxis.text.x element_textangle hjust
ggplotdf aesx age_group y salary
geom_boxplotfill
geom_jitterwidth alpha
ggplotdf aesx salary
geom_histogramaesy ..density.. bins fill
geom_densitycolor size
ggplottime_series_df aesx date y value
geom_linecolor
geom_point
scale_x_datedate_breaks date_labels
themeaxis.text.x element_textangle hjust
Statistical Analysis
summary(df)
mean(df$age)
median(df$salary)
sd(df$age)
var(df$salary)
quantile(df$age, probs = c(0.25, 0.5, 0.75))
cor(df$age, df$salary)
cor.test(df$age, df$salary)
t.test(df$salary ~ df$gender)
model <- aov(salary ~ age_group, data = df)
summary(model)
TukeyHSD(model)
lm_model lmsalary age experience data df
summarylm_model
new_data data.frameage experience
predictlm_model new_data interval
multi_model lmsalary age experience education data df
summarymulti_model
parmfrow
plotmulti_model
logit_model glmoutcome age salary
data df
family binomiallink
summarylogit_model
Time Series Analysis
library(forecast)
ts_data <- ts(data, start = c(2020, 1), frequency = 12)
decomposed <- decompose(ts_data)
plot(decomposed)
auto_arima <- auto.arima(ts_data)
summary(auto_arima)
forecast_result <- forecast(auto_arima, h = 12)
plot(forecast_result)
accuracy(forecast_result)
Machine Learning
library(caret)
library(randomForest)
set.seed(123)
train_index <- createDataPartition(df$outcome, p = 0.8, list = FALSE)
train_data <- df[train_index, ]
test_data <- df[-train_index, ]
rf_model <- randomForest(
outcome ~ .,
data = train_data,
ntree = 500,
importance = TRUE
)
predictions <- predict(rf_model, test_data)
confusionMatrix(predictions, test_data$outcome)
importance(rf_model)
varImpPlotrf_model
train_control trainControl
method
number
savePredictions
cv_model train
outcome .
data train_data
method
trControl train_control
printcv_model
R Markdown
---
title: "Analysis Report"
author: "Data Scientist"
date: "`r Sys.Date()`"
output:
html_document:
toc: true
toc_float: true
code_folding: hide
---
This analysis explores the relationship between variables.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
library(tidyverse)
Data Loading
df <- read.csv("data.csv")
head(df)
Visualization
ggplot(df, aes(x = x, y = y)) +
geom_point() +
theme_minimal()
Results
The analysis shows that r cor(df$x, df$y) correlation.
## Data Import/Export
```r
# CSV
df <- read.csv("data.csv")
write.csv(df, "output.csv", row.names = FALSE)
# Excel
library(readxl)
library(writexl)
df <- read_excel("data.xlsx", sheet = "Sheet1")
write_xlsx(df, "output.xlsx")
# JSON
library(jsonlite)
df <- fromJSON("data.json")
write_json(df, "output.json")
# Database
library(DBI)
library(RSQLite)
con <- dbConnect(SQLite(), "database.db")
df <- dbReadTable(con, "table_name")
dbWriteTable(con, "new_table", df)
dbDisconnect(con)
# Web APIs
library(httr)
response <- GET("https://api.example.com/data")
data <- content(response, as = "parsed")
Best Practices
Code Style
- Use <- for assignment
- Follow tidyverse style guide
- Write functions for repeated code
- Use meaningful variable names
- Comment complex operations
- Use %>% pipe for readability
Data Analysis
- Always explore data first
- Check for missing values
- Validate assumptions
- Use visualization
- Document your analysis
- Make analysis reproducible
Performance
- Vectorize operations
- Use data.table for large data
- Avoid growing objects in loops
- Profile code with Rprof()
- Use parallel processing
- Cache expensive computations
Anti-Patterns
❌ Growing vectors in loops
❌ Not setting random seed
❌ Ignoring NA values
❌ Using attach()
❌ Not documenting code
❌ Hardcoding file paths
❌ Not checking assumptions
Resources