Data Journey

International Studies Grad. racing for AI Engineer

Download as .zip Download as .tar.gz View on GitHub
30 January 2021

Matrix

by mervyn

source “K-MOOC 오세종 교수님의 [R 데이터 분석 입문] 강좌의 3-1. matrix 중 (http://www.kmooc.kr/courses/course-v1:DKUK+DKUK0003+2020_T3)”

2D data

  1. matrix: should be same data type
  2. 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

  1. Create a score matrix
>score
      m  f
[1,] 10 21
[2,] 40 60
[3,] 60 70
[4,] 20 30
  1. Nmae columns as male, female

  2. Print all values in row 2

  3. Print all values in female

  4. 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]

back next Index

tags: R

Comments

Post comment
Loading...

Share this: