R Basics Practice Notebook

  1. Assigning values to variables in R and printing it
#Using assignment operator
match.score <- 300
#print variable content
match.score
## [1] 300
#Using assign function
assign("match.score",300) 
#print variable content
match.score 
## [1] 300

Global environment setup

match.score <- 300 #assign variable in global environment
match.score  #get variable from global environment
## [1] 300
get("match.score",globalenv())  #get variable from global environment
## [1] 300

Create Custom environment

my.environment <- new.env() #create a new custom environment
parent.env(my.environment) #Check parent environment
## <environment: R_GlobalEnv>

Assign a variable in custom environment

assign("match.score",320,my.environment) #assign a variable in custom environment
my.environment[["match.score"]] <- 320 #assign a variable in custom environment
my.environment$match.score <- 320 #assign a variable in custom environment

Get variable from custom environment

get("match.score",my.environment)
## [1] 320
my.environment[["match.score"]] #get variable of custom environment
## [1] 320
my.environment$match.score #get variable of custom environment
## [1] 320

Using R As Calculator(Arithmetic Operators)

10 + 5  #Addition
## [1] 15
10 - 5  #Subtraction
## [1] 5
10 * 5  #Multiplication
## [1] 50
10 / 5  #Division
## [1] 2
10 ^ 5  #Exponentiation
## [1] 1e+05
format(10 ^ 5, scientific=FALSE) #Without scientific notation
## [1] "100000"
10 ** 5 #Exponentiation
## [1] 1e+05
10 %% 3  #Modulus 
## [1] 1
10 %/% 3  #Integer division
## [1] 3
#Mathematical functions
abs(-5)  #Absolute 
## [1] 5
log(2) #Natural logarithm
## [1] 0.6931472
log(2,base = 10 ) #Logarithm
## [1] 0.30103
exp(5) #Exponential
## [1] 148.4132
factorial(5) #factorial
## [1] 120
#Special constants
pi #PI
## [1] 3.141593

Special Numbers in R

#Infinity
1 / 0 #Positive infinity
## [1] Inf
-1 / 0 #Negative infinity
## [1] -Inf
Inf + 5 #Operation on Inf
## [1] Inf
is.finite(1 / 0) #Check if finite
## [1] FALSE
is.infinite(1 / 0) #Check if infinite
## [1] TRUE
#Undefined
Inf / Inf #NaN (Not a Number)
## [1] NaN
is.nan(Inf/Inf) #Check if NaN
## [1] TRUE
#Missing values
NA + 5 #Operation on NA
## [1] NA
is.na(NA) #Check if NA
## [1] TRUE
#NaN is NA , but NA is not NaN
is.na(NaN) #Check if NaN is NA
## [1] TRUE
is.nan(NA) #Check if NA is NaN
## [1] FALSE

Logical Operators in R

5 > 2  #greater than
## [1] TRUE
5 >= 2 #greater than equal to 
## [1] TRUE
5 < 2  #less than
## [1] FALSE
5 <=2  #less than equal to
## [1] FALSE
5 == 2 #exactly equal to
## [1] FALSE
5 != 2 #not equal to
## [1] TRUE
"b" > "a" #comparing characters
## [1] TRUE
!(TRUE) #logical NOT operator
## [1] FALSE
TRUE | FALSE #logical OR operator
## [1] TRUE
TRUE & FALSE #logical AND Operator
## [1] FALSE