Exercise 4: GGPLOT2 in R
Group manipulation and data reshaping in R,
understanding the philosophy of ggplot2, bar plot, pie chart, histogram,
boxplot, scatter plotand
regression plots
1. Write R Script for Group Manipulation
and Data Reshaping
For
following data
Group |
A |
A |
B |
B |
C |
C |
Value |
10 |
15 |
12 |
18 |
8 |
14 |
Answer:
# Install
the dplyr package if not already installed
if
(!require(dplyr)) {
install.packages("dplyr")
}
if
(!require(tidyr)) {
install.packages("tidyr")
}
library(dplyr)
library(tidyr)
# Load
necessary libraries
library(dplyr)
# Create a
sample dataset
data <-
data.frame(
Group = c("A", "A",
"B", "B", "C", "C"),
Value = c(10, 15, 12, 18, 8, 14)
)
# Group
manipulation: Calculate the mean value for each group
group_means
<- data %>%
group_by(Group) %>%
summarise(Mean_Value = mean(Value))
# Data
reshaping: Convert to wide format
wide_data
<- pivot_wider(group_means, names_from = Group, values_from = Mean_Value)
# Print the
result
print(wide_data)
OUTPUT
# A tibble: 1 × 3
A B C
<dbl> <dbl> <dbl>
1 12.5 15 11
1. 2. Display
scatterplot for two variables by assigning random values to them using ggplot2.
OUTPUT
3. 3. Display Histogram for two variables by
assigning random values to them using GGPLOT2.
44.
Display Boxplot by assigning random data using GGPLOT2 with multiple
colours and labels wherever possible.
4. Display piechart by assigning random data using GGPLOT2 with multiple
colours and labels wherever possible.
6. Display scatterplot with regression line by assigning random data using
GGPLOT2 with multiple colours and labels wherever possible.
Comments
Post a Comment