x1 <- c(2,3,5)
names(x1)
## NULL
names(x1) <- c("a","b","ab")
names(x1)
## [1] "a" "b" "ab"
x1
## a b ab
## 2 3 5
names(x1) <- NULL
x1
## [1] 2 3 5
names(x1) <- c("a","b","ab")
x1["b"]
## b
## 3
y1<-matrix(c(2,3,4,5),nrow=2,ncol=2)
y1
## [,1] [,2]
## [1,] 2 4
## [2,] 3 5
y1<-matrix(c(2,3,4,5),nrow=2)
y1
## [,1] [,2]
## [1,] 2 4
## [2,] 3 5
y1[,2]
## [1] 4 5
8.Specify elements for MATRIX individually.
y2 <- matrix(nrow=2,ncol=2) #Note! we need to warn R ahead of time that 'y2' will be a matrix and give the number of rows and columns.
y2[1,1] <- 3
y2[2,1] <- 4
y2[1,2] <- 5
y2[2,2] <- 6
y2
## [,1] [,2]
## [1,] 3 5
## [2,] 4 6
m1 <- matrix(c(2,3,4,5,6,7),nrow=2,byrow=T)
m1
## [,1] [,2] [,3]
## [1,] 2 3 4
## [2,] 5 6 7
y1
## [,1] [,2]
## [1,] 2 4
## [2,] 3 5
y1 %*% y1 # mathematical matrix multiplication
## [,1] [,2]
## [1,] 16 28
## [2,] 21 37
3*y1 # mathematical multiplication of matrix by scalar
## [,1] [,2]
## [1,] 6 12
## [2,] 9 15
y1+y1 # mathematical matrix addition
## [,1] [,2]
## [1,] 4 8
## [2,] 6 10
z1 <- matrix(nrow=4,ncol=3) #create matrix 4x3 and assign values
z1[1,1] <- 2
z1[2,1] <- 3
z1[1,2] <- 2
z1[2,2] <- 2
z1[3,1] <- 4
z1[3,2] <- 1
z1[3,3] <- 2
z1[1,3] <- 2
z1[2,3] <- 1
z1[4,1] <- 5
z1[4,2] <- 1
z1[4,3] <- 1
z1
## [,1] [,2] [,3]
## [1,] 2 2 2
## [2,] 3 2 1
## [3,] 4 1 2
## [4,] 5 1 1
z1[,2:3] #extracts all elements with column 2,3 and any row number
## [,1] [,2]
## [1,] 2 2
## [2,] 2 1
## [3,] 1 2
## [4,] 1 1
z1[2:1,] #extract rows 2,1
## [,1] [,2] [,3]
## [1,] 3 2 1
## [2,] 2 2 2
x2<-c(2,13,6,14,17,9)
x2
## [1] 2 13 6 14 17 9
x2 <- c(x2,22) # append 22
x2
## [1] 2 13 6 14 17 9 22
x2 <- c(x2[1:3],33,x2[4:6]) # insert 33
x2
## [1] 2 13 6 33 14 17 9
x2 <- x2[-2:-4] # delete elements 2 through 4
x2
## [1] 2 14 17 9
two<-c(2,2,2,2)
two
## [1] 2 2 2 2
z1
## [,1] [,2] [,3]
## [1,] 2 2 2
## [2,] 3 2 1
## [3,] 4 1 2
## [4,] 5 1 1
cbind(two,z1) #creates new matrix by combining a column of 2s with the columns of z
## two
## [1,] 2 2 2 2
## [2,] 2 3 2 1
## [3,] 2 4 1 2
## [4,] 2 5 1 1
z2 <- cbind(z1,two) #creates new matrix by combining a column of 2s with the columns of z and saves it to new DF
z2
## two
## [1,] 2 2 2 2
## [2,] 3 2 1 2
## [3,] 4 1 2 2
## [4,] 5 1 1 2
cbind(2,z1) #same function as line 111 (reling on recycling)
## [,1] [,2] [,3] [,4]
## [1,] 2 2 2 2
## [2,] 2 3 2 1
## [3,] 2 4 1 2
## [4,] 2 5 1 1
q <- cbind(c(2,3),c(4,5))
q
## [,1] [,2]
## [1,] 2 4
## [2,] 3 5
m <- matrix(1:6,nrow=3)
m
## [,1] [,2]
## [1,] 1 4
## [2,] 2 5
## [3,] 3 6
m <- m[c(1,3),]
m
## [,1] [,2]
## [1,] 1 4
## [2,] 3 6