R programming learning
R Programming Basic
R programming
Author
Prof CKDash
Published
September 10, 2025
Introduction
This eBook demonstrates how to include R code, plots, tables, and real images.
Example Dataset
We will analyze pest infestation levels across crops.
library(reshape2)
library(ggplot2)
Warning: package 'ggplot2' was built under R version 4.4.3
library(knitr)
Warning: package 'knitr' was built under R version 4.4.3
pest_data <- data.frame(
Crop = c("Tomato","Brinjal","Chili"),
Low = c(5, 3, 6),
Medium = c(7, 6, 4),
High = c(2, 4, 5)
)
pest_data
Crop Low Medium High
1 Tomato 5 7 2
2 Brinjal 3 6 4
3 Chili 6 4 5
Pest Infestation Bar Plot
df <- melt(pest_data, id.vars="Crop")
colnames(df) <- c("Crop","Pest_Level","Count")
ggplot(df, aes(x=Crop, y=Count, fill=Pest_Level)) +
geom_bar(stat="identity", position="dodge") +
labs(title="Pest Infestation by Crop Type",
x="Crop Type", y="Number of Plots") +
theme_minimal()
# Adding an Image (Fertilizer Example)
Sometimes we want to **visually explain concepts**.
Here we include an image of fertilizer and crop yield.
{width=50%}
And here is a picture of healthy crop yield:
{width=50%}
> 📌 Place your images in a folder called `images/` inside your project directory.
Correlation Example (Fertilizer vs Yield)
set.seed(123)
fertilizer <- seq(50, 250, 10)
yield <- 0.4 * fertilizer + rnorm(length(fertilizer), mean=10, sd=5)
data <- data.frame(fertilizer, yield)
ggplot(data, aes(x=fertilizer, y=yield)) +
geom_point(color="darkgreen", size=3) +
geom_smooth(method="lm", se=FALSE, color="blue") +
labs(title="Correlation between Fertilizer and Crop Yield",
x="Fertilizer (kg/ha)", y="Yield (t/ha)") +
theme_minimal()
`geom_smooth()` using formula = 'y ~ x'
Data Table (Formatted)
knitr::kable(
pest_data,
caption = "Pest Infestation Summary",
align = "c"
)
Pest Infestation Summary
CropLowMediumHigh
Tomato572
Brinjal364
Chili645
Conclusion
This eBook combines R code, outputs, tables, plots, and real images.
You can use it for agricultural research, training, or extension materials.