Matrix
by mervyn
source “K-MOOC 오세종 교수님의 [R 데이터 분석 입문] 강좌의 3-1. matrix 중 (http://www.kmooc.kr/courses/course-v1:DKUK+DKUK0003+2020_T3)”
2D data
- matrix: should be same data type
- data frame: available for mix of characters and numbers. Should be same data type in a column
create matrix
z<- matrix(1:20, nrow=4, ncol=5) #nrow: number of row, ncol: number of column
z # We usually call matrix data from file
z<-matrix(1:20, nrow=4, ncol=5, byrow=T) # byrow: direction of row
z
Combine vector(s) with matrix(ces)
x<- 1:4
y<- 5:8 # vector x and y
m1<- cbind(x,y) #column bind: combine in column direction
m2<- rbind(x,y) # row bind: combine in row direction
m1
m2
m3<- rbind(m2,x)
m4<- cbind(z, x)
m3
m4
index[]: location inside of matrix
z<- matrix(1:20, nrow=4, ncol=5)
z[2,3] # row 2, col 3
z[1,4]
z[2,] # all values in row 2
z[,4] # all values in col 4
If you bring one row/column from matrix, the data structure become 1D vector
Naming Row and Column
rownames(z) # null
colnames(z) # null
rownames(z)<- c("row1", "row2", "row3", "row4")
colnames(z)<- c("col1", "col2", "col3", "col4", "col5")
Call data by name
z[,"col3"]
z["row2",]
Assignment
- Create a score matrix
>score
m f
[1,] 10 21
[2,] 40 60
[3,] 60 70
[4,] 20 30
-
Nmae columns as male, female
-
Print all values in row 2
-
Print all values in female
-
Print value of row 3, column 2
m<- c(10, 40, 60, 20)
f<- c(21, 60, 70, 30)
score<- cbind(m,f)
score
colnames(score)<-c("male", "female")
score
score[2,]
score[,"female"]
score[3,2]
Comments
Post comment