0% found this document useful (0 votes)
6 views10 pages

huzz

The document covers various topics in R programming, including the use of the concatenating function to create vectors, advanced data structures like data frames and lists, and control structures such as if-else statements and for loops. It also discusses data entry methods, the Grammar of Graphics for visualizations using ggplot2, and probability distributions with functions like pnorm, dbinom, and dpois. Additionally, it provides examples of generating random data and performing statistical calculations.

Uploaded by

kamranbajwa019
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)
6 views10 pages

huzz

The document covers various topics in R programming, including the use of the concatenating function to create vectors, advanced data structures like data frames and lists, and control structures such as if-else statements and for loops. It also discusses data entry methods, the Grammar of Graphics for visualizations using ggplot2, and probability distributions with functions like pnorm, dbinom, and dpois. Additionally, it provides examples of generating random data and performing statistical calculations.

Uploaded by

kamranbajwa019
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
You are on page 1/ 10

R Language Topics

1. Concatenating Function in R: The concatenating function in R, c(), is used to combine


multiple values into a single vector. It works with numbers, characters, or other data types
and is one of the most commonly used functions in R.
Example:

vec <- c(1, 2, 3, 4, 5)

vec

2. Vector Definition through Concatenating Function: A vector is created in R using


the c() function, which combines values into a single vector.

Example:

vec <- c(1, 2, 3, 4, 5)

vec

3. Vector Numerical and Arithmetic Operations: R allows element-wise arithmetic


operations on vectors.

Example:

##Vectors

vec1 <- c(1, 2, 3)

vec2 <- c(4, 5, 6)

##Operations

sum_vec <- vec1 + vec2 # Addition

diff_vec <- vec1 - vec2 # Subtraction

prod_vec <- vec1 * vec2 # Multiplication

div_vec <- vec1 / vec2 # Division

sum_vec

Page 1 of 10
R Language Topics
4. Advanced Data Structures:
• Vectors: A vector in R is a one-dimensional data structure that holds an ordered
collection of elements of the same type (numeric, character, or logical).
Example:
vec <- c(1, 2, 3, 4, 5)
• Data Frame: A tabular structure where columns can have different data types.
Example:

D <- data.frame(Name = c("Ali", "Sara"), Age = c(25, 30), Score = c(85, 90))

• Data Matrix: A matrix with all elements of the same type.

Example:

M <- matrix(1:9, nrow = 3, ncol = 3)

• List: A collection of different types of data.

Example:

L <- list(vec, D, M)

5. Control Structures: Are expressions used to control the execution and flow of the
program based on the conditions provided in the statements. These structures are used
to decide after assessing the variable.

6. if and else statements: The if and else statements in R are fundamental control
structures used to perform conditional execution of code blocks.

if (condition) {
An if statement checks a condition, and if
If # Code to execute if condition is TRUE
it is TRUE, the associated code block runs.
}

if (condition) {
# Code to execute if condition is TRUE
The else statement provides an alternative
Else } else {
action when the if condition is not met.
# Code to execute if condition is FALSE
}

Page 2 of 10
R Language Topics
7. ifelse statement:
The ifelse function in R is a vectorized
ifelse checks the condition for each element in
conditional statement that evaluates a logical
a vector and assigns different outcomes
condition for each element of a vector and
based on whether the condition is met (TRUE)
returns a specified value for TRUE and
or not (FALSE).
another for FALSE. It is useful for performing
Syntax:
element-wise conditional operations
ifelse(condition, true statement, false
efficiently.
statement)

Example:
• if-else Statement:

x <- 2

if (x > 3) {

print("x is greater than 3")

} else {

print("x is less than or equal to 3")

• ifelse Function:

vec <- c(5, 2, 8)

result <- ifelse(vec > 3, "High", "Low")

print(result)

8. For Loops in R: A for loop in R is used to repeat a block of code a specific number of
times. It is often used for iterating over a sequence of values (e.g., numbers, vectors, or
lists).
Example:

for (i in 1:5)

Page 3 of 10
R Language Topics
{

print(paste("Value is:", i))

9. Data Entry in R: Data entry in R refers to the methods used to input data into R from
various sources, such as manual input, external files, or user input.

• Manual Entry:

data <- c(1, 2, 3, 4, 5)

print(data)

• Read from File:

df <- read.csv("data.csv")

print(df)

• User Input:

D <- c()

D <- edit(D)

10. Grammar of Graphics (ggplot2):

The Grammar of Graphics in R, implemented through the ggplot2 package, is a system for
creating complex, layered visualizations. It allows users to describe plots using a consistent
framework that includes data, aesthetic mappings, geometric objects, and statistical
transformations.

• Use: ggplot2 is used to create a wide range of visualizations (e.g., bar charts, line plots,
scatter plots) and is popular due to its flexibility and ability to create highly customizable
plots.

• Key Components:

Page 4 of 10
R Language Topics
o Data: The dataset you want to plot.

o Aesthetics (aes): Mappings of variables to visual properties like x and y axes, color,
shape, etc.

o Geometric Objects (geom): The actual elements of the plot, like points, lines, bars,
etc.

o Facets: Create subplots based on a factor variable.

o Themes: Control the appearance of the plot (background color, grid lines, etc.).

Example:

library(ggplot2)

##Create a simple scatter plot

df <- data.frame(x = c(1, 2, 3, 4), y = c(4, 3, 2, 1))

ggplot(df, aes(x = x, y = y)) + geom_point() ##Scatter plot of x vs y

11. Probability and Probability Distribution:

Normal distribution (use of pnorm and qnorm):

1. pnorm(): The pnorm() function in R is used to compute the cumulative distribution


function (CDF) of the normal distribution. It gives the probability that a random variable
from a normal distribution is less than or equal to a specific value.

Use: pnorm() is useful for finding the cumulative probability up to a certain point in a
normally distributed dataset.

Syntax: pnorm(q, mean = 0, sd = 1)

2. qnorm():The qnorm() function is the inverse of pnorm(). It computes the quantile for a
given cumulative probability. In other words, it finds the value corresponding to a specific
cumulative probability in a normal distribution.

Page 5 of 10
R Language Topics
Use: qnorm() is used to determine the value (or threshold) for a given probability
in a normal distribution.

Syntax: qnorm(p, mean = 0, sd = 1)

3. dnorm() : The dnorm() function in R is used to calculate the probability density (height of
the probability density function) at a specific value for a normal distribution. It returns
the value of the normal distribution's probability density function (PDF) for a given point.

Use: You use dnorm() when you want to compute the density of the normal
distribution at a particular value. This is useful for understanding how likely or "dense" a
particular value is in a normal distribution.

Syntax: dnorm(x, mean = 0, sd = 1)

4. rnorm() in R: The rnorm() function generates random samples from a normal distribution.
It is used to simulate data that follows the normal (Gaussian) distribution, defined by its
mean (μ) and standard deviation (σ).
Use: Use rnorm() when you need to create random data that approximates a
normal distribution, which is common in statistical modeling, testing, and simulations.
Syntax: rnorm(n, mean = 0, sd = 1)

Example:

1. Generating Random Normal Data:

Generate 10 random numbers from a standard normal distribution (μ=0, σ=1):

rnorm(10)

# Output: e.g., -0.5605, 0.2304, -1.2402, 0.6523, etc.

2. Specifying Mean and Standard Deviation:

Generate 5 random numbers from a normal distribution with μ=50 and σ=10:

rnorm(5, mean = 50, sd = 10)

Page 6 of 10
R Language Topics
# Output: e.g., 45.231, 60.123, 47.456, etc.

Binomial distribution (Use of dbinom and pbinom):

1. dbinom(): The dbinom() function calculates the probability of exactly k successes in a


binomial distribution with a given number of trials (n) and success probability (p).

Use: You use dbinom() when you want to find the probability of observing exactly k
successes out of n trials.

Syntax: dbinom(k, size = n, prob = p)

Example: Find the probability of getting exactly 3 heads in 5 flips of a fair coin (probability of
heads = 0.5):

dbinom(3, size = 5, prob = 0.5)

# Output: 0.3125 (Probability of exactly 3 heads)

2. pbinom(): The pbinom() function calculates the cumulative probability of getting up to k


successes in a binomial distribution with a given number of trials (n) and success
probability (p). It returns the probability of getting k or fewer successes.

Use: You use pbinom() when you want to find the probability of getting k or fewer
successes out of n trials.

Syntax: pbinom(k, size = n, prob = p)

Example: Find the probability of getting 3 or fewer heads in 5 flips of a fair coin:

pbinom(3, size = 5, prob = 0.5)

# Output: 0.8125 (Probability of getting 3 or fewer heads)

3. qbinom(): The qbinom() function computes the quantile (or threshold value) for a given
cumulative probability in a binomial distribution. In simpler terms, it answers the
question: "What is the number of successes below which the cumulative probability is p?"

Page 7 of 10
R Language Topics
Use: You use qbinom() when you want to find the minimum number of successes
required to achieve a given cumulative probability.
Syntax: qbinom(p, size, prob)

Example: Find the number of successes needed to reach at least 95% cumulative probability in a
binomial distribution with 10 trials and a success probability of 0.5:

qbinom(0.95, size = 10, prob = 0.5)

# Output: 8

4. rbinom(): The rbinom() function in R generates random samples from a binomial


distribution. It is useful for simulating outcomes of binomial experiments.
Use: Use rbinom() when you need to simulate or generate random data that
follows a binomial distribution, such as the number of successes in a fixed number of
trials.
Syntax: rbinom(n, size, prob)

Example:

Generating Random Data: Simulate the number of heads obtained when flipping a fair coin 10
times, repeated 5 times:

rbinom(5, size = 10, prob = 0.5)

# Output: e.g., 5, 6, 4, 7, 5

Piossion distribution (Use of dpois, ppois, qpois, and rpois):

1. dpois():

• Purpose: To calculate the probability of observing exactly k events in a Poisson


distribution.

• Use Case: When you need the probability of a specific outcome.

Page 8 of 10
R Language Topics
• Syntax: dpois(k, lambda)

• Example: Probability of exactly 3 events occurring when λ=5:

dpois(3, lambda = 5)

# Output: 0.1403739

2. ppois():

• Purpose: To calculate the cumulative probability of k or fewer events.

• Use Case: When you need the probability of observing up to a certain number of events.

• Syntax: ppois(k, lambda)

• Example: Probability of observing 3 or fewer events when λ=5:

ppois(3, lambda = 5)

# Output: 0.2650259

3. qpois():

• Purpose: To find the value of k (number of events) that corresponds to a given cumulative
probability.

• Use Case: When you need to determine the threshold for a specific cumulative probability.

• Syntax: qpois(p, lambda)

• Example: Number of events needed to achieve a cumulative probability of 0.8 when λ=5:

qpois(0.8, lambda = 5)

# Output: 7

4. rpois():

• Purpose: To generate random samples from a Poisson distribution.

• Use Case: When you need simulated data or random values from a Poisson process.

Page 9 of 10
R Language Topics
• Syntax: rpois(n, lambda)

• Example: Generate 10 random values from a Poisson distribution with λ=5:

rpois(10, lambda = 5)

# Output: Random numbers (e.g., 4, 6, 5, 3, etc.)

Page 10 of 10

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy