R Programming - Lecture - 24-06-2023
R Programming - Lecture - 24-06-2023
> 4*x
Matrix Operations
Matrix multiplication: operator %*%
Consider the multiplication of X’ with X
> xtx <- t(x) %*% x
> xtx
Cross product of a matrix X, X’X, with a function crossprod
> xtx2 <- crossprod(x)
> xtx2
Note: Command crossprod()executes the
multiplication faster than the
conventional method with t(x)%*%x
Matrix Operations
Addition and subtraction of matrices (of same dimensions) can be
executed with the usual operators + and -
> x <- matrix(nrow=4, ncol=2, data=1:8, byrow=T)
>x
> 4*x
> x + 4*x
> X – 4*x
Matrix Operations
Access to rows, columns or submatrices:
> x <- matrix( nrow=5, ncol=3, byrow=T, data=1:15)
>x
> x[3,]
> x[,2]
> x[4:5, 2:3]
Matrix Operations
Inverse of a matrix:
solve() finds the inverse of a positive definite matrix
> y<- matrix( nrow=2, ncol=2, byrow=T, data=c(84,100,100,120))
>y
> solve(y)
Missing Data
R represents missing observations through the data value NA
We can detect missing values using is.na
> x <- NA # assign NA to variable x
> is.na(x) # is it missing?
Now try a vector to know if any value is missing?
> x <- c(11, NA, 13)
> is.na(x)
Missing Data
How to work with missing data?
> x <- c(11,NA,13) # vector
> mean(x)
> mean(x, na.rm = TRUE) # NAs can be removed
Control structures in R
Syntax
if (condition) {executes commands if condition is TRUE}
if (condition) {executes commands if condition is TRUE}
else { executes commands if condition is FALSE }
Please note:
• The condition in this control statement may not be vector valued
and if so, only the first element of the vector is used.
Example:
> x <- 5
if ( x==3 ) { x <- x-1 } else { x <- 2*x }
Interpretation:
• If x = 3, then execute x = x – 1.
• If x ≠ 3, then execute x = 2*x.
In this case, x = 5, so x ≠ 3. Thus x = 2*5
>x
if and else
> x <- 3
> if ( x==3 ) { x <- x-1 } else { x <- 2*x }
Interpretation:
• If x = 3, then execute x = x – 1.
• If x ≠ 3, then execute x = 2*x.
In this case, x = 3, so x = 3 – 1
>x