Introduction To R: # Creating A Vector of Numbers

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Introduction to R

Soumya Roy
# Creating a Vector of Numbers
x<-c(1,2,3,4)
x

## [1] 1 2 3 4

# Creating Two Vectors


x<-c(1,2,3)
x

## [1] 1 2 3

y<-c(4,5,6)
y

## [1] 4 5 6

# Length of a Vector
length(x)

## [1] 3

length(y)

## [1] 3

# Addition of Two Vectors


x+y

## [1] 5 7 9

# Multiplication by a Constant Number


c<-2
c*x

## [1] 2 4 6

c*y

## [1] 8 10 12

# Looking at a list of all of the objects


ls()

## [1] "c" "x" "y"


# Deleting the variable
rm(x,y)

# Checking the list of current objects


ls()

## [1] "c"

# Deleting the variables


rm(list=ls())

# Creating a matrix of numbers


# R always fills the columns first
X<-matrix(c(1,2,3,4),nrow=2,ncol=2)
X

## [,1] [,2]
## [1,] 1 3
## [2,] 2 4

# Dimension of a Matrix
dim(X)

## [1] 2 2

# Creating a matrix of numbers by filling up the rows first


X<-matrix(c(1,2,3,4),nrow=2,ncol=2,byrow=T)
Y<-matrix(c(5,6,7,8),nrow=2,ncol=2,byrow=T)

# Addition of Two Matrices


A<-X+Y

# Multiplication of Two Matrices


Z<-X%*%Y

# Inverse of Matrix
I<-solve(X)

# Accessing elements of a matrix


A<-matrix(1:9,3,3)

# Accessing (1,3)-th element


A[1,3]

## [1] 7

# Accessing multiple rows


A[c(1,2),]
## [,1] [,2] [,3]
## [1,] 1 4 7
## [2,] 2 5 8

# Accessing multiple columns


A[,c(2,3)]

## [,1] [,2]
## [1,] 4 7
## [2,] 5 8
## [3,] 6 9

# Accessing Multiple Rows and Columns


A[c(1,2),c(2,3)]

## [,1] [,2]
## [1,] 4 7
## [2,] 5 8

# Deleting a particular row


A[-c(1),]

## [,1] [,2] [,3]


## [1,] 2 5 8
## [2,] 3 6 9

# Deleting a particular column


A[,-c(1)]

## [,1] [,2]
## [1,] 4 7
## [2,] 5 8
## [3,] 6 9

You might also like