Data type : vector, data frame, matrix(array), factor, list
자료형 확인 및 정의 : as.character(x), as.complex(x) , as.numeric(x) or as.double(x),
as.integer(x), as.logical(x)
vector : 백터는 동질적dls 같은 자료형으로 같은 모드를 가지고 있어야 한다. 하나의 값으로 구성된 백터가 스칼라이고
여러개 있으면 벡터
data frame : 데이터를 열을 기준으로 정리한 것으로 표 형태의 데이터를 표현하기 위함이다.
x <- 1:10 # mean(x) # sd(x) # var(x)
행은 모두 같은 길이이며, 열은 하나의 엘리먼트를 나타낸다. 행렬과 다른점은 각각의 행들이 서로다른 데이터 타입들을 가질 수 있다는 것이다.
즉, 각각의 열들은 같은 타입으로 이뤄지지만, 모든 열이 모두 같을 필요는 없다.
data.matrix() : 행렬을 data frame으로 변경 할 수 있다.
데이터 프레임 합치기는 cbind # 두개의 데이터를 열로 쌓고, rbind # 두개의 데이터를 행으로 쌓는다.
matrix(array) : vector 에 차원을 정해준 것이 바로 Matrix이다. 백터의 dim 속성이 처음엔 NULL 이지만 이것을 주게 되면 matrix가 된다.
dim(2,3) # 2 by 3 행렬 /
Array (배열)
3차원 matrix 부터는 배열이라는 이름을 쓴다.
Factor(요인) : 요인들은 간단하고 효율적인 형태로 데이터 프레임에 저장되어 특별한 속성이 있다. R은 백터에 있는 고유한 값(unique value)의 정보를 얻어 내는데, 이 고유 값들을 요인의 '수준(level)'이라고 일컫는다.
요인의 범주형 변수 기능으로, 분할표, 선형 회귀, 변량 분석, 로지스틱 회귀 분석에 사용 된다.
집단 분류 기능은 데이터 항목에 라벨을 붙이거나 태깅을 할 때 쓰는 방법이다.factor( x, levels, ordered #TRUE=순서형, FALSE=명목형 데이터) / nlevels(x) / 중간에 값 넣기 ;
factor(append(as.character(gender),"TRUE"))
list : 이질적인 다양한 자료형을 포함 할수 있다.
연속적인 리스트라면, do.call(rbind,mylist) 이용 모두 행열이 같은 크기일때만 가능하다.
서로다른 데이터 프레임 합치기는 merge 일치하는 부분만 합치고 싶으면, merge(A,B, by="열 이름")
으로 설정한다.
Data manipulation
( source code 참조 ) 수와 계산 : / 변수 : / 제어 : / 비교와 블리언 : / 조건문 : / 입력과 출력 : / 논리 연산 :
/ Plot/ Bart chart /. Histogram / Scree Chart / 자료형 확인 및 정의 : as.character(x),
as.complex(x) , as.numeric(x) or as.double(x)
Function :
rnorm_fixed = function(n, mu=0, sigma=1) {
x = rnorm(n) # from standard normal distribution
x = sigma * x / sd(x) # scale to desired SD
x = x - mean(x) + mu # center around desired mean
return(x)
}
#1. multicollinearity check : cor(iris[1:4]) ; # some of them are big as 0.87
# 2. biased data -> transform log / log_ir <- log(iris[, 1:4])
데이터가 편향된 경우 사용 (skip도 가능) / ir_species <- iris[,5]
# 3. pca analysis : # Unlike princomp, prcomp : variances are computed with the usual
divisor N - 1.
ir_pca <- prcomp(log_ir, center = T, scale. = T)
train, test dataset 으로 구분하여 성능 확인도 가능
# 4. plot scree graph : plot(ir_pca,type="lines")
# 5. summary : check that how much it has a power of explanation Cumulative Proportion
summary(ir_pca)/ # Cumulative Proportion 0.7331 of PC1, 0.9599 with PC2
# 6. linear regression : prc <- as.matrix(log_ir) %*% ir_pca$rotation # skip 가능
## 1. goodness of fit test : chisq.test() / obs <- c(19, 40, 35) /
prob <- c(2/10, 3/10, 5/10) / chisq.test(obs, p=prob)
## indexing / chisq.test() of data from data frame /
# chisq.test() of data from data frame / data(Cars93, package="MASS") /
Car_Type <- table(Cars93$Type)
# giving names to the rows and columns of the data table : dimnames()
/ dimnames(dt) <- list("Class" = c("Class_1", "Class_2", "Class_3"),
"Score" = c("Score_H", "Score_M", "Score_L", "Fail"))
## exploratory data analysis /
# marginal distribution : addmargins() /
addmargins(dt) / prop.table(dt)
addmargins(prop.table(dt)) / # bar plot : barplot(t(dt), beside=TRUE, legend=TRUE,
ylim=c(0, 30),
ylab="Observed frequencies in sample",
main="Frequency of math score by class")
# indexing statistics of chisq.test() /
fit <- chisq.test(dt) /
fit$observed # observed frequency /
fit$expected # expected frequeycy /
fit$residuals # residual between observed and expected frequecy /
fit$statistic # chi-squared statistics /
fit$parameter # degrees of freedomfit /
fit$p.value # P-value
비지도 학습으로 계층적 방식과, k-means 방식이 있으며, 크게 절차는
데이터 준비, 분석, 예측 및 성능 검증으로 이루어 진다.
hierarchical clustering algorithm :
## a : hierarchical clustering algorithm , clu <- hclust(dist(iris[, 3:4])) / plot(clu) # generates the following dendrogram: clu_cut <- cutree(clu, 3) # cut off the tree at the desired
number of clusters using cutree