벡터, 행렬의 연산 및 함수

벡터 및 행렬 생성

# 벡터, 행렬의 연산 및 함수

# 1. 벡터 및 행렬 생성
# 1.1 벡터 생성
# vector
x <-c(1,3,5,7,9)
x[3] # R index는 1부터 / python은 0부터

# subset of vector : delete the first element 
x[-1] # 첫번쨰 값 삭제

# subset of vector : delete the first two elemen
x1 <- x[-c(1,2)] # 첫번째, 두번쨰 값 삭제
x1

# subset of vector : delete the 1st to the 3rd element
x2 <- x[-c(1:3)]
x2

# create vector using 'seq'
# sequence of 20 values
y1 <-seq(0,10, length=20) #
# sequence of (1 to 10) by 0.5
y2 <-seq(0,10, by=0.5)

# using rep
z1 <- rep(1:4,2)
z1
z2 <-rep(1:2,5)
z2

# combine vectors in a row or column
# cbind : column bind(열 기준으로 결합)
c1 <- c(2,4,6,8,10)
c2 <- cbind(x, c1)
c2
# rbind : row bind (행으로 결합)
c3 <-rbind(x,c1)
c3

# 벡터이름 정의
# Give name to a vector
gender <- c(0,1)
names(gender) <- c('female','male')
gender
length(gender)

# categorical varaibles : factor
size <-c ('S','M','L','XL')
# define size as a factor (categorical), 순서없음
size_factor <- factor(size)
size_factor

is.factor(size_factor)

# give order for categorical variable
size_factor3 <- factor(size, ordered = TRUE, levels = c('S','M','L','XL'))
size_factor3

# create matrix
# two row matrix with 1 to 10
m1 <- matrix(1:10, nrow=2)
m1
m2 <- matrix(1:6, ncol=3)
m2

# matrix filled by rows, defalut : fillled by cloumns 
m3 <- matrix(1:6, nrow=2, byrow=T)
m3
help(matrix)

# higher order of array
a1 <- array(c(1:18), dim=c(3,3,2))
a1
a1[,,1]
a1[,,2]

벡터 생성

seq(처음, 시작, length=, by=)

rep(처음:시작, 반복횟수)

 

벡터 결합

cbind (열기준)

rbind (행기준)

벡터이름정의

names(벡터) <- c('이름1','이름2')

범주형 변수 생성 (categorical)

factor(벡터, ordered=, levels = )

행렬의 생성

matrix(처음,시작, nrow=, ncol=, byrow= ) : 1열부터 채우는 것이 default

고차원 행렬의 생성

array(c(처음:끝),  dim=c(행:열:차원)

 

벡터와 행렬의 연산

기본연산기호

Operator Description Operatpr Description
+ addition == exactly equl to
- subtraction !x Not x
* multiplication x | y x OR y
/ division x & y  x AND y
^ or ** exponentiation is TRUE(x) test if X is TRUE
x %% y modulus(x mod y) 5%%2 is 1    
x %/% y integer division 5 %/%2 is 2    

행렬의 연산

Operator or Function Description
A*B Element-wise multiplication1
A%*%B Matrix multiplication
A%o%B Outer product AB'
crossprod(A,B) A'B and A'A respectively
crossprod(A)  
t(A) Transpose
solve(A) Inverse of A where A is a squre matrix
y<-eigen(A) y$val are the eigenvalues of A
y$vec are the eigenvectors of A  
y<-svd(A) Sigle value decomposition of A 
y$d = vector containing the singular values of A
y$u = matrix with columns contain the left singular vectors of A
y$v = matrix with columns contain the right singular vectors of A
R <- chol(A) Choleski factorization of A. Returns the upper triangular factor, such that R'R = A
cbind(A,B,...) Combine matrices(vectors) horizontally. Returns a matrix.
rbind(A,B,...) Combine matrices(vectors) vertically. Returns a matrix.
rowSums(A) Returns vector of row sums.
colMeans(A)  Returns vector of column means.
colSums(A) Returns vector of column sums.

전치행렬 : t()

determinant : det()

역행렬 : solve()

역행렬을 이용한 방정식 해 구하기 : slove(a,b)

고유치와 고유 벡터 : eigen(공분산행렬) / eigen(t(x)%*%x)

 

# 벡터와 행렬의 연산
## 기본 연산

# calculation
2^3
4**3
7%%5
7%/%5

# 행렬의 연산
# matrix eample (2*5)
m1 <- marix(1:10, nrow=2)
m1

# dimension of m1
dim(m1)

m2<-matrix(1:6, ncol=3)
m2

# transpose of m2
tm2 <-t(m2)
tm2
# determinant of matrix
d1<-matrix(1:4, nrow=2, byrow=T)
d1
det(d1)

# inverse of matrix
d1_inv <-solve(d1)
d1_inv

# d1*inv(d1) = identity matrix
d1%*%d1_inv

# solve equation
a <- matrix(c(3,1,2,1), nrow=2, ncol=2)
b <- matrix(c(8,2), nrow=2, ncol=1)
a
b
solve(a,b)
help(solve)

# example for eigen value and eigen vector
# already centered matrix
x <- matrix(c(-3,-3,0,1,2,2,-3,-3,0,2,2,2,5,7,4,0,-5,-11), nrow=6, ncol=3)
x
dim(x)

# eigen value and eigen vector
el <- eigen(t(x)%*%x) # 공분산 행렬렬
el

간단한 함수 생성 및 루프

# create a simple function 

# square function

square <-function(x){
  return(x*x)
}
square(9)
square(1:3)

dif <-function(x,y){
  return(x-y)
}
dif(20,10)

rootdif <- function(x,y){
  return(sqrt(x-y))
}
rootdif(20,10)

# round off the decimal point
round(5.14846)
round(5.14846, 2)

# to see the function 'round'
round
round(rootdif(20,10))
round(rootdif(20,10),2)

# creating loop
# for 1 to 10
# if remainder=1 when deviding by 3
# then go to next number

for(i in 1:10){
  if(i%%3==1){
    next()
  }
  print(i)
}

# for loop example2
# stop loop after sum>20
sum = 0
for (i in 1:10) {
  sum<-sum+i
  if(sum>20){
    # stop loop after sum>20
    break
  }
  print(sum)
}

# whlie loop
# while (condition) {expression}
y=0
while(y<5){print(y<-y+1)}

'Data Science > R' 카테고리의 다른 글

[R] 폴더 안의 파일 목록 가져오기  (0) 2022.12.08