0% found this document useful (0 votes)
13 views4 pages

R Functions for Descriptive Statistics

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views4 pages

R Functions for Descriptive Statistics

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computational Statistics Lab (24M11MA175)

Dr. Priyanka A. Jha


PMS Department
JU- Anoopshahr(India)

R Codes For Descriptive statistics and Probalibity distribusition

Some useful R functions for performing statistical analysis, categorized by dif-


ferent types of analysis:
(1) Basic Descriptive Statistics
(a) mean(): Calculates the arithmetic mean.
(b) median(): Returns the median.
(c) mode(): R does not have a built-in mode function, but you can cal-
culate the mode using:
(i) Mode <- function(x) { [Link](names(sort(table(x), decreas-
ing=TRUE)[1])) } Mode(data)
(d) var(): Calculates the variance. var(data)
(e) sd(): Computes the standard deviation.
(f) range(): Provides the minimum and maximum values.
(g) IQR(): Computes the interquartile range (Q3 - Q1).
(h) quantile(): Calculates specic percentiles or quantiles.
(i) quantile(data, probs = c(0.25, 0.5, 0.75))
(2) Summary Statistics
(a) summary(): Provides a quick summary of data, including min, max,
quartiles, and mean.
(b) summary(data)
(c) describe() (from psych package): Provides detailed descriptive sta-
tistics, including skewness and kurtosis.
(i) library(psych) describe(data)
(3) Distribution Functions:
(a) Normal distribution functions (density, probability, quantile, random
generation).
• dnorm(), pnorm(), qnorm(), rnorm()
• # Generate random normal data
• data <- rnorm(100, mean=0, sd=1)
(b) Similar functions exist for other distributions like binomial, Poisson,
and Chi-Square-distribution:
• Binomial distribution: dbinom(), pbinom(), rbinom()
• Poisson distribution: dpois(), ppois(), rpois()
• Chi-Square -distribution: dchisq(), pchisq(), qchisq(), rchisq()
(4) Visualization for Statistical Analysis
(a) boxplot(): Visualizes the distribution of data via a boxplot. box-
plot(data)
(b) hist(): Creates a histogram for visualizing the frequency distribution
of data. hist(data)
(c) plot(): General plotting function; useful for scatterplots and basic
data visualization.
(d) plot(x, y) ggplot2: A powerful library for creating a variety of plots.
1
R CODES FOR DESCRIPTIVE STATISTICS AND PROBALIBITY DISTRIBUSITION 2

• Example for a boxplot: library(ggplot2) ggplot(data, aes(x = fac-


tor(Age_Group), y = Cholesterol_Level)) + geom_boxplot()
(5) Random Sampling sample(): Draws a random sample from a vector.
sample(data, size = 10, replace = TRUE)
These functions and methods are foundational in R for conducting statistical anal-
yses, ranging from simple descriptive statistics to more advanced hypothesis testing
and regression analysis.
Problem: A health research institute conducted a study to analyze the choles-
terol levels of individuals across dierent age groups. The dataset consists of choles-
terol levels (in mg/dL) of 50 individuals from three dierent age groups: 20-30, 31-
40, and 41-50. Perform the following descriptive statistical analysis using Python:
Calculate the mean, median, and mode of cholesterol levels for the entire
dataset.
Determine the range, variance, and standard deviation of cholesterol levels.
Compute the 25th, 50th (median), and 75th percentiles.
Provide a summary for each age group including the mean, variance, and stan-
dard deviation of cholesterol levels.
Create a boxplot to visualize the distribution of cholesterol levels across the
three age groups.
Solution : Using R. Mean, Median, Mode:
The mean(), median(), and mode() functions are used to calculate the corre-
sponding statistics. The mode is calculated using a frequency table with table()
and nding the highest frequency. Range, Variance, Standard Deviation:
The range() function returns the minimum and maximum values of cholesterol
levels. Variance is calculated with var(), and standard deviation with sd(). Per-
centiles:
The quantile() function is used to calculate the 25th, 50th (median), and 75th
percentiles. Descriptive Statistics for Each Age Group:
The dataset is grouped by the "Age Group" column using group_by() from
dplyr. Summary statistics (mean, variance, standard deviation) are calculated for
each age group using summarise(). Boxplot Visualization:
The ggplot2 library is used to create a boxplot of cholesterol levels by age group.
geom_boxplot() is called on the dataset to visualize the distribution.
# Load necessary libraries
library(dplyr)
library(ggplot2)
library(psych) # For descriptive statistics
# Sample dataset
data <- [Link](
Age_Group = c("20-30", "20-30", "20-30", "20-30", "20-30", "31-40", "31-40",
"31-40", "31-40", "31-40", "41-50", "41-50", "41-50", "41-50", "41-50"),
Cholesterol_Level = c(190, 210, 180, 200, 195, 220, 240, 230, 225, 235, 250,
270, 260, 255, 265)
)
# 1. Calculate mean, median, mode for the entire dataset
mean_chol <- mean(data$Cholesterol_Level)
median_chol <- median(data$Cholesterol_Level)
Table 1. Function Code in R and Excel for Statistics
Statistic R Code Excel
Mean mean(data) AVERAGE(range)
Median median(data) MEDIAN(range)
Mode<-function(x){ [Link](range)
Mode [Link](names(sort(table(x),
decreasing=TRUE)[1]))}
Variance var(data) VAR.P(range)
Standard Deviation Standard Deviation(data) STDEV.P(range)
Skewness skewness(x) SKEW(range)
Kurtosis kurtosis(x) KURT(range)
Min min(data) MIN(range)
Max max(data) MAX(range)
Range range(data) MAX(range) - MIN(range)
Interquartile Range(IQR) IQR(data) [Link](range, 3) - [Link](range, 1)
Quantile/Percentiles quantile(data, probs = c(0.25, 0.5, 0.75)) [Link](range, k)
Frequency Distribution table(x) FREQUENCY(data_array, bins_array)
Summary Statistics summary(data) summary(data)
R CODES FOR DESCRIPTIVE STATISTICS AND PROBALIBITY DISTRIBUSITION
3
R CODES FOR DESCRIPTIVE STATISTICS AND PROBALIBITY DISTRIBUSITION 4

Table 2. Excel code for Probability Distribution

Distribution Excel
Binomial [Link](number_s, trials, probability_s, cumulative)
Normal [Link](x, mean, standard_dev, cumulative)
Poisson [Link](x, mean, cumulative)
Chi-Square [Link](x, degrees_freedom, cumulative)

mode_chol <- [Link](names(sort(table(data$Cholesterol_Level), decreas-


ing=TRUE)[1]))
cat("Mean Cholesterol:", mean_chol, "\n")
cat("Median Cholesterol:", median_chol, "\n")
cat("Mode Cholesterol:", mode_chol, "\n")
# 2. Calculate range, variance, and standard deviation
chol_range <- range(data$Cholesterol_Level)
chol_variance <- var(data$Cholesterol_Level)
chol_sd <- sd(data$Cholesterol_Level)
cat("Range of Cholesterol Levels:", chol_range[2] - chol_range[1], "\n")
cat("Variance of Cholesterol Levels:", chol_variance, "\n")
cat("Standard Deviation of Cholesterol Levels:", chol_sd, "\n")
# 3. Calculate the percentiles
percentiles <- quantile(data$Cholesterol_Level, probs = c(0.25, 0.5, 0.75))
cat("25th Percentile:", percentiles[1], "\n")
cat("50th Percentile (Median):", percentiles[2], "\n")
cat("75th Percentile:", percentiles[3], "\n")
# 4. Descriptive stats for each age group
grouped_stats <- data %>%
group_by(Age_Group) %>%
summarise(
Mean = mean(Cholesterol_Level),
Variance = var(Cholesterol_Level),
SD = sd(Cholesterol_Level)
)
print("Descriptive Statistics by Age Group:")
print(grouped_stats)
# 5. Create a boxplot to visualize the distribution across age groups
ggplot(data, aes(x=Age_Group, y=Cholesterol_Level)) +
geom_boxplot() +
labs(title = "Boxplot of Cholesterol Levels by Age Group",
x = "Age Group",
y = "Cholesterol Level (mg/dL)") +
theme_minimal()

Common questions

Powered by AI

Boxplots and histograms are instrumental in visualizing cholesterol level distributions as they succinctly convey data spread, central tendency, and potential outliers. Boxplots highlight quartiles and medians, showing variations across age groups, while histograms display frequency distributions, enabling the identification of skewness and modality in data. Combined, they provide a comprehensive visual interpretation of distribution patterns, aiding in hypothesis generation and validation .

Variance and standard deviation are calculated in R using the var() and sd() functions, respectively. Variance provides the average of the squared differences from the mean, offering insight into data spread. Standard deviation, the square root of variance, is expressed in the same units as the mean, making it more interpretable. Both metrics identify variability but standard deviation is often more intuitively used for comparing variations across datasets .

R does not have a built-in function for calculating the mode. Instead, it is calculated by creating a frequency table using the table() function and then identifying the value with the highest frequency. The calculation is done with a custom function, Mode <- function(x) { as.numeric(names(sort(table(x), decreasing=TRUE)[1])) }, which sorts the frequency table in descending order and selects the first value .

The ggplot2 package in R provides a flexible and powerful system for creating informative and aesthetically pleasing visualizations. When visualizing cholesterol levels across age groups, ggplot2 allows for easy customization of plots, aesthetic mappings, and the addition of statistical transformations. For instance, using geom_boxplot() to visualize distribution provides clear insights into the spread and central tendency of cholesterol levels, which aids in the comparison between groups .

Probability distribution functions like dnorm() and pnorm() are crucial in understanding and analyzing the behavior of datasets as they provide the density and cumulative distribution functions for normal distribution, respectively. They allow statisticians to compute probabilities, quantiles, and to simulate data, enabling the analysis of how data conforms to theoretical distributions, thus facilitating inferential statistics and hypothesis testing .

Random normal data can be generated in R using the rnorm() function. The function takes parameters such as sample size, mean, and standard deviation. For example, data <- rnorm(100, mean=0, sd=1) creates a dataset of 100 random values from a normal distribution with mean of 0 and a standard deviation of 1. This is useful for simulations and testing statistical methods under known conditions .

The summary() function in R provides a quick overview of a dataset by showing the minimum, maximum, mean, and quartiles. It is useful for a quick assessment of basic properties. The describe() function, from the psych package, offers a more detailed analysis, including additional measures like skewness and kurtosis, which are useful for understanding the shape and distribution characteristics of the data .

The interquartile range (IQR) provides a measure of statistical dispersion, which is less affected by outliers than range or standard deviation. It is useful in understanding the spread of the middle 50% of cholesterol levels, offering a robust metric to describe variability. In R, the IQR is computed using the IQR() function, which calculates the difference between the 75th and 25th percentiles .

R's sample() function is advantageous for random sampling because it allows selection of random elements from a dataset, providing options to specify sample size and whether sampling should be done with replacement. This capability is crucial for bootstrapping, simulations, and validating statistical models through resampling techniques, thereby providing robustness checks and reducing bias in analysis .

R differentiates between age groups using data manipulation functions such as group_by() from dplyr, allowing analysis to be conducted within each group. Functions such as summarise() are used to compute statistics like mean, variance, and standard deviation for the cholesterol levels within each group. This method facilitates understanding of how statistical properties vary across distinct demographic segments .

You might also like