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 |
# 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
=========================================================================================================================================
Comments
Post a Comment