0% found this document useful (0 votes)
23 views

P2 - Basics of R Programming

The document provides an overview of basic concepts in R programming including help commands, comments, naming conventions, keywords, operators, data types, and data structures. It describes three ways to get help in R using help(), ? and ??, lists rules for naming objects, and covers arithmetic, relational, logical and assignment operators. It also defines the main data types in R as numeric, character, logical, complex and integer, and describes common data structures like vectors, lists, matrices, data frames, factors and arrays.

Uploaded by

Sukhpal Rajpoot
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

P2 - Basics of R Programming

The document provides an overview of basic concepts in R programming including help commands, comments, naming conventions, keywords, operators, data types, and data structures. It describes three ways to get help in R using help(), ? and ??, lists rules for naming objects, and covers arithmetic, relational, logical and assignment operators. It also defines the main data types in R as numeric, character, logical, complex and integer, and describes common data structures like vectors, lists, matrices, data frames, factors and arrays.

Uploaded by

Sukhpal Rajpoot
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

BASICS OF R PROGRAMMING

HELP COMMAND IN R
Help command
describe the in- >help(keyword_name)
built keyword. >?keyword_name
There are three >??keyword_name
ways to get >help.start() #whole help
description document/tutorial
about a inbuilt- >apropos(‘some part of keyword
keyword, name’) #list out the matching
package or keywords
function in R.
COMMENTS
• Single Line Comment
> # This Line is a Comment
> a = 5 # After assignment in variable a, rest line is a comment
>
NAMES
• Symbols Allowed in a name: {. and _}
• All numerical values {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} are allowed.
• All characters {a-z and A-Z} are allowed.
• Only . and characters are allowed to start a name and rest can be used anywhere.
• R is a case sensitive language.
• Some names are restricted in R (they are called reserved keywords).
TRUE
else FALSE

NaN

if NULL

NA_real_ Inf

functio
break KEYWORDS n

NA_integer NA_character_

next for
NA_complex_

NA while
repeat
OPERATORS
1. ARITHMETIC OPERATORS
2. RELATIONAL OPERATORS
3. LOGICAL OPERATORS
4. ASSIGNMENT OPERATORS
5. MISCELLANEOUS OPERATORS
OPERATORS
ARITHMETIC
Operator
OPERATORS Description Example Result
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 6-2 3
^ or ** Exponentiation 2^3 8
%% Modulus (Remainder) 10 %% 3 1
%/% Integer Division 10 %/% 3 3
- (Unary) Unary Minus (Negation) -5 -5
%*% Matrix Multiplication M %*% N Result
OPERATORS
RELATIONAL OPERATORS
Operator Description Example Result
< Less than 5 < 10 TRUE
<= Less than or equal to 5 <= 10 TRUE
> Greater than 5 > 10 FALSE
>= Greater than or equal to 5 >= 10 FALSE
== Equal to 5 == 5 TRUE
!= Not equal to 5 != 10 TRUE
%in% Value exists in a vector 5 %in% c(1, 2, 3, 4, 5) TRUE
! Negation (not) !(5 == 10) TRUE
OPERATORS
LOGICAL OPERATORS
Operator Description Example Result
& Logical AND TRUE & FALSE FALSE
&& Short-circuit AND TRUE && FALSE FALSE
| Logical OR TRUE | FALSE TRUE
|| Short-circuit OR TRUE || FALSE TRUE
! Logical NOT !TRUE FALSE
Exclusive OR
xor() xor(TRUE, FALSE) TRUE
(XOR)
Check if object is
isTRUE() isTRUE(5 > 3) TRUE
TRUE
Check if any are
any() any(c(FALSE, FALSE, TRUE)) TRUE
TRUE
Check if all are
all() all(c(TRUE, TRUE, FALSE)) FALSE
OPERATORS
ASSIGNMENT OPERATORS
Operato
r Description Example Result
Standard assignment operator. Assigns a
<- or = x <- 5 or x = 5 x contains 5
value to a variable.

Assignment to a parent environment Variable x in a parent


<<- x <<- 5
(used in functions). environment is set to 5

Right-assignment operator. Assigns a


-> or ->> 5 -> x x contains 5
value to a variable on the right.

Assigns a value to a variable with a


assign() assign("y", 10) y contains 10
specified name.

Assigns a value to a component of an


$ my_list$a <- 42 my_list$a contains 42
object.
OPERATORS
MISCELLANEOUS OPERATORS
Operator Description Example

Colon Operator (:) Creates a sequence of numbers 1:5 generates 1, 2, 3, 4, 5

Membership Operator (%in


Checks if an element belongs to a vector 5 %in% c(1, 2, 3, 4, 5)
%)
Checks if an element does not belong to a
Not in Operator (!%in%) 6 !%in% c(1, 2, 3, 4, 5)
vector

Existence Operator (exists()) Checks if a variable or object exists exists("x")

Removes variables or objects from the


Remove Operator (rm()) rm(x)
environment
Assigns a value to a variable with a specified
Assign Operator (assign()) assign("y", 10)
name
Facilitates chaining of operations in data
Pipe Operator (%>%) data %>% filter(cond) %>% select(cols)
manipulation
Accesses functions or objects from specific
Namespace Operator (::) dplyr::select(data, cols)
packages
Accesses help documentation for
Help Operator (?) ?mean displays help for mean function
functions/packages
character

raw numeric

Data
Type
s
complex integer

logical
DATA TYPES
Data Type Syntax Description

numeric A = 50 or A = 50.85 or A = NaN or Numeric data type is used to store


A = NA_real_ numeric values, including integers
and real numbers (floating-point).
character A = “[email protected]” Character data type is used to store
text or strings of characters.
raw A = charToRaw(“Waste of Time”) Raw data type is used to store
binary data as a sequence of bytes.

logical A = TRUE or A = FALSE or A = Logical data type is used to store


NA Boolean values, which can be
either TRUE or FALSE.
complex A = 4+5i or A = NA_complex_ Complex data type is used to store
complex numbers with both real
and imaginary parts.
integer A = 500L or A = NA_integer_ Integer data type is used to store
whole numbers without fractional
parts.
DATA STRUCTURES
Vectors
Lists
Matrices
Data Frames
Factors
Arrays
Tables
DATA STRUCTURES
VECTORS
VECTORS ARE ONE-DIMENSIONAL ARRAYS THAT CAN HOLD HOMOGENEOUS
ELEMENTS OF THE SAME DATA TYPE, SUCH AS NUMBERS, CHARACTERS, OR
LOGICAL VALUES.
EXAMPLE:
>NUMERIC_VECTOR <- c(1, 2, 3, 4, 5)
>CHARACTER_VECTOR <- c("APPLE", "BANANA", "CHERRY")
>LOGICAL_VECTOR <- c(TRUE, FALSE, FALSE)
DATA STRUCTURES
LISTS
LISTS ARE ONE-DIMENSIONAL DATA STRUCTURES THAT CAN HOLD ELEMENTS OF
DIFFERENT DATA TYPES. EACH ELEMENT CAN BE A VECTOR, A LIST, OR ANY OTHER
R DATA STRUCTURE.
EXAMPLE:
> MY_LIST1 <- list(1, "APPLE", C(2, 3, 4))
> MY_LIST2 <- list(NUMERIC_VECTOR, CHARACTER_VECTOR, LOGICAL_VECTOR)
DATA STRUCTURES
MATRICES
MATRICES ARE TWO-DIMENSIONAL ARRAYS WITH ROWS AND COLUMNS. ALL
ELEMENTS IN A MATRIX MUST BE OF THE SAME DATA TYPE.
EXAMPLE:
> MY_MATRIX <- matrix(1:9, nrow = 3, ncol = 3 , byrow = TRUE)
DATA STRUCTURES
DATA FRAMES
DATA FRAMES ARE TWO-DIMENSIONAL TABULAR DATA STRUCTURES SIMILAR TO
SPREADSHEETS OR DATABASE TABLES. THEY CAN STORE DATA OF DIFFERENT
DATA TYPES IN COLUMNS..
EXAMPLE:
 MY_DATAFRAME <- data.frame( name = c("ALICE", "BOB", "CHARLIE"),
age = c(25, 30, 35),
score = c(95, 88, 72))
DATA STRUCTURES
FACTORS
FACTORS ARE USED TO REPRESENT CATEGORICAL DATA. THEY ARE OFTEN USED IN
STATISTICAL MODELING.
EXAMPLE:
> MY_FACTOR <- factor(c("HIGH", "MEDIUM", "LOW", "HIGH", "LOW"))
DATA STRUCTURES
ARRAYS
ARRAYS ARE MULTI-DIMENSIONAL DATA STRUCTURES THAT CAN STORE
ELEMENTS OF THE SAME DATA TYPE. THEY ARE LIKE EXTENSIONS OF MATRICES.
EXAMPLE:
> MY_ARRAY <- array(1:24, dim = c(2, 3, 4))
DATA STRUCTURES
TABLES
TABLES ARE SIMILAR TO DATA FRAMES BUT ARE USED FOR HANDLING DATA IN
THE FORM OF CONTINGENCY TABLES, OFTEN USED IN STATISTICAL ANALYSIS.
EXAMPLE:
> MY_TABLE <- table(c("A", "B", "A", "C", "B", "C"))
CONDITIONAL STATEMENTS
if statement:
if-else statement:
if-else if-else Statement:
switch Statement:
CONDITIONAL STATEMENTS
IF STATEMENT:
THE IF STATEMENT ALLOWS YOU TO EXECUTE A BLOCK OF CODE
IF A SPECIFIED CONDITION IS TRUE.

Syntax: Example:
if (condition) { x <- 10
# Code to execute if if (x > 5) {
condition is TRUE print("x is greater than
} 5")
}
CONDITIONAL STATEMENTS
IF-ELSE STATEMENT:
THE IF-ELSE STATEMENT ALLOWS YOU TO EXECUTE ONE BLOCK
OF CODE IF A CONDITION IS TRUE AND ANOTHER BLOCK IF IT IS
FALSE.
Syntax: Example:
if (condition) { x <- 3
# Code to execute if if (x > 5) {
condition is TRUE print("x is greater than 5")
} else { } else {
# Code to execute if print("x is not greater than
condition is FALSE 5")
} }
CONDITIONAL STATEMENTS
 IF-ELSE IF-ELSE STATEMENT:

THE IF-ELSE IF-ELSE STATEMENT ALLOWS YOU TO CHECK MULTIPLE


CONDITIONS AND EXECUTE THE CORRESPONDING BLOCK OF CODE BASED ON
THE FIRST CONDITION THAT IS TRUE.
Syntax: Example:
if (condition1) { x <- 7
# Code to execute if condition1 is
if (x > 10) {
TRUE
} else if (condition2) { print("x is greater than 10")
# Code to execute if condition2 is } else if (x > 5) {
TRUE print("x is greater than 5 but
} else { not greater than 10")
# Code to execute if all conditions } else {
are FALSE
print("x is 5 or less")
}
}
CONDITIONAL STATEMENTS
 SWITCH STATEMENT:

THE SWITCH STATEMENT ALLOWS YOU TO SELECT ONE OF


SEVERAL CODE BLOCKS TO EXECUTE BASED ON THE VALUE OF
AN EXPRESSION.
Syntax:
switch(expression,
Example:
case1 = { day <- "Monday"
# Code to execute for case1
}, switch(day,
case2 = { "Monday" = print("It's the
# Code to execute for case2
}, start of the week!"),
default = {
# Code to execute if none of the cases
"Friday" =
match print("TGIF!"),
}
) print("It's just another
day.")
LOOPS
for Loop:
while Loop:
repeat Loop:
foreach Loop using
library(foreach)
LOOPS
 FOR LOOP:

THE FOR LOOP IS USED TO ITERATE OVER A SEQUENCE (E.G., A


VECTOR) OR A FIXED NUMBER OF TIMES.

Syntax: Example:
for (variable in sequence) for (i in 1:5)
{ {
# Code to execute for
each iteration
print(paste("Iteratio
} n", i))
}
LOOPS
 WHILE LOOP:

THE WHILE LOOP IS USED TO REPEATEDLY EXECUTE A BLOCK OF


CODE AS LONG AS A SPECIFIED CONDITION IS TRUE.

Syntax: Example:
while (condition) { x <- 1
# Code to execute while while (x <= 5) {
the condition is TRUE print(paste("x is", x))
} x <- x + 1
}
LOOPS
 REPEAT LOOP:

THE REPEAT LOOP IS USED TO CREATE AN INFINITE LOOP, WHICH


CAN BE EXITED USING THE BREAK STATEMENT WHEN A CERTAIN
CONDITION IS MET.
Syntax: Example:
repeat { x <- 1
# Code to execute repeat {
repeatedly print(paste("x is", x))
if (condition) { x <- x + 1
break # Exit the loop if (x > 5) {
when the condition is met break
} }
} }
FUNCTIONS
IN R, FUNCTIONS ARE BLOCKS OF REUSABLE CODE THAT
PERFORM A SPECIFIC TASK OR CALCULATION. FUNCTIONS ARE
ESSENTIAL FOR ORGANIZING AND SIMPLIFYING YOUR CODE.
Syntax: Example:
my_function <- greet <- function(name =
"Guest")
function(argument1, {
argument2, ...) cat("Hello,", name, "!\n")
{ }
# Code to perform the task greet() # Outputs: Hello, Guest!
# Return a result using the greet("Alice") # Outputs: Hello,
'return' keyword Alice!
}
STRINGS
Strings in R represent text or character data. They are
used to store and manipulate textual information.
I. Creating Strings
II. String Length
III. String Concatenation
IV. String Indexing
V. String Subsetting
VI. String Comparison
VII. String Case Conversion
VIII.String Searching and Replacing
IX. String Splitting and Joining
X. String Formatting
STRINGS
 Creating Strings
You can create strings in R by enclosing text within single
or double quotation marks

my_string = "Hello, World!"


STRINGS

 String Manipulation
R provides various functions for manipulating strings,
such as paste(), substr(), toupper(), tolower(), and gsub(),
among others.
STRINGS
 String Length
Determine the length of a string using the nchar()
function.

my_string <- "Hello, World!"


length <- nchar(my_string)
length # Prints 13
STRINGS
 String Concatenation
To concatenate strings, use the paste() or paste0()
functions.

first_name <- “Sukhpal"


last_name <- “Rajpoot"
full_name <- paste(first_name, last_name)
STRINGS
 String Indexing
You can access individual characters in a string by using
square brackets [ ] and specifying the index.

my_string <- "Hello, World!"char <-


function(string, index){return(substr(string,
start = index, stop = index))}
first_char <- char(my_string,1)
# Returns "H"first_char
STRINGS
 String Subsetting
You can extract a portion of a string using the substr( )
function.

my_string <- "Hello, World!"


subset <- substr(my_string, start = 1, stop =
5)
STRINGS
 String Comparison
You can compare strings using operators like ==, !=, <,
and >. The result is a logical value.

string1 <- "apple"


string2 <- "banana"
is_equal <- (string1 == string2)
STRINGS
 String Case Conversion
Change the case of strings using functions like toupper()
and tolower().

my_string <- "Hello, World!"


upper_case <- toupper(my_string)
STRINGS
 String Searching and Replacing
Search for substrings in a string using function grepl() and
replace substrings using gsub().

my_string <- "The quick brown fox jumps over


the lazy dog."
has_fox <- grepl("fox", my_string)
If (has_fox){
replaced_string <- gsub("fox", "cat", my_string)
}
STRINGS
 String Splitting and Joining
You can split a string into substrings using strsplit() and
join substrings into a single string using paste().

my_string <- "apple,banana,grape"


substrings <- strsplit(my_string, ",")[[1]]
joined_string <- paste(substrings, collapse = ";")
STRINGS
 String Formatting
You can format strings using placeholders and the
sprintf() function.

name <- “Sukhpal"


profession <- “teacher”
formatted <- sprintf("My name is %s, and I am a
%d.", name, profession)
STRINGS
String Regular Expressions
Explore yourself!
PRACTICE

• INDEXING
• BUILTIN FUNCTIONS
• USER INPUT
ASSIGNMENT - 1
1. Create a function that checks if a given integer is even or odd. Print an appropriate message based on the
result.
2. Write a program that defines a function to calculate and print the sum of two user-input numbers.
3. Create a function to compute and return the factorial of a given positive integer. Test the function with
different input values.
4. Develop a function that converts temperatures between Celsius and Fahrenheit. Allow the user to choose
the conversion direction and input the temperature value.
5. Write a program that defines a function to calculate and return the mean, median, mode, min and max of a
numeric vector provided as input.
6. Define a function to generate the first 'n' terms of the Fibonacci sequence and print the sequence.
7. Write a function that checks if a given string is a palindrome (reads the same forwards and backwards).
Return TRUE or FALSE based on the result.
8. Develop a function to calculate simple interest and compound interest (monthly, quarterly and yearly)
based on user-input principal amount A, rate R, and time T.
9. Define a function that counts the number of words in a given sentence or string. Exclude punctuation and
consider spaces as word separators.
10. Develop a program that calculates and prints the Equated Monthly Installment (EMI) for a loan. Allow
users to input loan amount, interest rate, and loan tenure.
• 50 MARKS FOR MTE AND 50 MARKS FOR ETE
• DECIDE A DATE FOR MID TERM PRACTICAL EXAM IN FIRST WEEK OF OCTOBER

You might also like