all.x = TRUE


logical; 

if TRUE, then extra rows will be added to the output, one for each row in x that has no matching row in y. 

These rows will have 'NA's in those columns that are usually filled with values from y. 

The default is FALSE, so that only rows with data from both x and y are included in the output.


TRUE이면 y에 일치하는 행이없는 x의 각 행에 하나씩 추가 행이 출력에 추가됩니다.

이 행은 대개 y 값을 채운 해당 열에서 'NA'을 갖습니다.

기본값은 FALSE이므로 x와 y의 데이터가있는 행만 출력에 포함됩니다.





출처: https://www.rdocumentation.org/packages/data.table/versions/1.11.4/topics/merge

R - 기본함수 - paste / paste0

https://m.blog.naver.com/PostView.nhn?blogId=coder1252&logNo=220985161855&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F


paste() 공백과 이어 붙이기

paste0() 공백없이 이어 붙이기

변수

- sep=" " 
이어 붙일 때 사용할 구분문자

- collapse=" "
결과값 두 개 이상일 때 


##### 의사결정나무

library(tree)

iris.tr<-tree(Species~., iris)

plot(iris.tr)

text(iris.tr)



# 데이터를 7:3으로 분리 

library(party)

idx<-sample(2, nrow(iris), replace=T, prob=c(0.7, 0.3))

train.data<-iris[idx==2,]

test.data<-iris[idx==1,]


iris.tree<-ctree(Species~., data=train.data)

plot(iris.tree)


plot(iris.tree, type="simple")


# 예측된 데이터와 실제 데이터 비교

table(predict(iris.tree), train.data$Species)


# test data를 적용하여 적확성 확인

test.pre<-predict(iris.tree, newdata=test.data)

table(test.pre, test.data$Species)





##### 앙상블 분석

# 랜덤포레스트

library(randomForest)

idx<-sample(2, nrow(iris), replace=T, prob=c(0.7, 0.3))

train.data<-iris[idx==2,]

test.data<-iris[idx==1,]

r.f<-randomForest(Species~., data=train.data, ntree=100, proximity=T)


table(predict(r.f), train.data$Species)


plot(r.f)


varImpPlot(r.f)


# test data 예측

pre.rf<-predict(r.f, newdata=test.data)

table(pre.rf, test.data$Species)


plot(margin(r.f, test.data$Species))




# 성과분석

library(rpart)

library(party)

library(ROCR)


x<-kyphosis[sample(1:nrow(kyphosis), nrow(kyphosis), replace=F),]

x.train<-kyphosis[1:floor(nrow(x)*0.75),]

x.evaluate<-kyphosis[floor(nrow(x)*0.75):nrow(x),]

x.model<-cforest(Kyphosis~Age+Number+Start, data=x.train)

x.evaluate$prediction<-predict(x.model, newdata=x.evaluate)

x.evaluate$correct<-x.evaluate$prediction == x.evaluate$Kyphosis

print(paste("% of predicted classification correct"), mean(x.evaluate$correct))

x.evaluate$probabilities<-1-unlist(treeresponse(x.model, newdata=x.evaluate), 

                                   use.names=F)[seq(1, nrow(x.evaluate)*2, 2)]

pred<-prediction(x.evaluate$probabilities, x.evaluate$Kyphosis)

perf<-performance(pred, "tpr", "fpr")

plot(perf, main="ROC curve", colorize=T)


perf<-performance(pred, "lift", "rpp")

plot(perf, main="lift curve", colorize=T)





##### 로지스틱 회귀분석

b<-glm(Species~Sepal.Length, data=a, family=binomial)

summary(b)



'programing > R studio' 카테고리의 다른 글

merge 함수의 all.x = TRUE  (0) 2018.09.10
R - 기본함수 - paste / paste0  (0) 2018.08.22
주성분분석 사례  (0) 2018.07.29
계량적MDS와 비계량적MDS 예시  (0) 2018.07.29
시계열 분석 예제  (0) 2018.07.29

##### 주성분분석 사례

library(datasets)

data(USArrests)


# 두 개 이상의 변수에 대해 모든 가능한 산점도를 그림

pairs(USArrests, panel=panel.smooth, main="USArrests data") 


US.prin<-princomp(USArrests, cor=T)

summary(US.prin)


# 주성분들에 의해 설명되는 변동의 비율

screeplot(US.prin, npcs=4, type="lines")


# 네 개의 변수가 각각 주성분 comp.1~4까지 기여하는 가중치

loadings(US.prin)


# comp.1~4의 선형식을 통해 각 지역별로 얻은 결과를 계산

US.prin$scores


biplot(US.prin)



'programing > R studio' 카테고리의 다른 글

R - 기본함수 - paste / paste0  (0) 2018.08.22
의사결정나무/앙상블분석/로지스틱회귀분석  (0) 2018.07.30
계량적MDS와 비계량적MDS 예시  (0) 2018.07.29
시계열 분석 예제  (0) 2018.07.29
회귀분석 - lm  (0) 2018.07.02

##### 계량적MDS : cmdscale사례


library(MASS)

head(eurodist)

str(eurodist)

eurodist


# cmdscale() : 2차원으로 21개 도시들을 매핑

loc<-cmdscale(eurodist)

x<-loc[,1]

y<- -loc[,2] # 북쪽도시를 상단에 표시하기 위해 부호를 바꾼 것


plot(x, y, type="n", asp=1, main="Metric MDS") # asp=x축의 단위

text(x, y, rownames(loc), cex=0.7)

abline(v=0, h=0, lty=2, lwd=0.5) # v=x축; h=y축; lty=선타입; lwd=선굵기




##### 비계량적MDS : isoMDS와 sammon사례

library(MASS)

data(swiss)

swiss

head(swiss)


# iosMDS

swiss.x<-as.matrix(swiss[,-1])

swiss.dist<-dist(swiss.x) # 열과 데이터매트릭스간의 거리

swiss.mds<-isoMDS(swiss.dist) 

plot(swiss.mds$points, type="n")

text(swiss.mds$points, labels=as.character(1:nrow(swiss.x)))

abline(v=0, h=0, lty=2, lwd=0.5)

?isoMDS


# sammon

swiss.x<-as.matrix(swiss[,-1])

swiss.sammon<-sammon(dist(swiss.x))

plot(swiss.sammon$points, type="n")

text(swiss.sammon$points, labels=as.character(1:nrow(swiss.x)))

abline(v=0, h=0, lty=2, lwd=0.5)

'programing > R studio' 카테고리의 다른 글

의사결정나무/앙상블분석/로지스틱회귀분석  (0) 2018.07.30
주성분분석 사례  (0) 2018.07.29
시계열 분석 예제  (0) 2018.07.29
회귀분석 - lm  (0) 2018.07.02
기하분포 - dgeom  (0) 2018.07.02

library(tseries)

library(forecast)

library(TTR)

king<-scan("http://robjhyndman.com/tsdldata/misc/kings.dat", skip=3)

king


# ts = time series = 시계열

# ts(데이터) = 시계열 객체 생성하기

# start=첫 번째 관찰 타임; end=마지막 관찰 타임; frequency=세부적인 관찰 주기

king.ts<-ts(king)


# plot.ts(시계열 데이터) : 시계열 데이터를 그래프로 표현 

plot.ts(king.ts)




# 3년마다 평균을 내서 그래프를 부드럽게 표현

# SMA() : 지난 n 회의 관측치에 대한 시계열의 산술 평균을 계산

king.sma3<-SMA(king.ts, n=3)

plot.ts(king.sma3)


# 8년마다 평균을 내서 그래프를 부드럽게 표현

king.sma8<-SMA(king.ts, n=8)

plot.ts(king.sma8)



# ARIMA모델

# 1차 차분(현시점자료-전시전자료)

king.ff1<-diff(king.ts, differences=1)

plot.ts(king.ff1)



# ACF와 PACF를 통해 적합하 ARIMA모델을 결정

acf(king.ff1, lag.max=20)

acf(king.ff1, lag.max=20, plot=F)


pacf(king.ff1, lag.max=20)

pacf(king.ff1, lag.max=20, plot=F)



# auto.arima() : 자동으로 적합한 arima모델을 찾아줌

auto.arima(king)

king.arima<-arima(king.ts, order=c(0,1,1))

king.arima


# forecast() : 미래 예측 

# 책에는 forecast.Arima()로 나오는데, 그건 작동이 안 됨

king.forecasts<-forecast(king.arima, h=5)

king.forecasts

plot(king.forecasts)

'programing > R studio' 카테고리의 다른 글

주성분분석 사례  (0) 2018.07.29
계량적MDS와 비계량적MDS 예시  (0) 2018.07.29
회귀분석 - lm  (0) 2018.07.02
기하분포 - dgeom  (0) 2018.07.02
ggplot2 - scale_x_discrete, scale_y_discrete - x, y값 순서 정렬  (0) 2018.06.29

숫자 있는 셀만 선택

찾기 및 선택-이동 옵션-수식 


일괄적으로 문자 앞 뒤에 특정 문자 표시하기

컨트롤+1 - 사용자 지정 - "(특정문자)"@


일괄적으로 숫자 뒤에 특정 문자 표시하기

컨트롤+1 - 사용자 지정 - "(특정문자)"


숫자인 셀 개수 알아내기

=COUNT(범위)


언급된 횟수 알아내기?

=COUNTIF(범위, 조건)


일의 자릿수 버리기

=ROUNDDOWN(숫자, -1)


일의 자릿수에서 무조건 반올림 하기

=ROUNDUP(숫자, -1)


IF 와 AND/OR

=IF(AND(조건1,조건2),TRUE일 때,FALSE일 때)

=IF(OR(C7>=70,D7="제출"),"합격","탈락")


다중 IF

=IF(E4>=90,"A",IF(E4>=80,"B",IF(E4>=70,"C",IF(E4>=60,"D","E"))))


IF 와 COUNTIF

=IF(COUNTIF($B$3:$B$9,B3)>1,"중복","")


시간/날짜

오늘 날짜: 컨트롤 + ;

2018-07-19


현재 시간: 컨트롤 + :

1:51 PM


=TODAY()

2018-07-19


범위에서 키워드에 해당하는 내용이 있으면 더해라

=SUMIF(범위,"키워드",더할 범위)

=SUMIF(B3:B58,"중동점",F3:F58)


다양한 조건의 범위에서 키워드에 해당하는 내용만 더하기

=SUMIFS(실제 더할 셀 범위,조건1 범위,"키워드",조건2 범위,"키워드")

=SUMIFS(F3:F58,B3:B58,"중동점",C3:C58,"아이패드")


중간 글자 추출

=MID(데이터, 시작할 순서, 몇글자)

=MID(C5,8,1)

C5데이터의 8번째 글자 하나 추출


1~125숫자에 따라 추출

=CHOOSE(데이터, 1을 추출할때의 결과값, 2~, ..., 125~)

=CHOOSE(MID(C5,8,1),"남자","여자","남자","여자")

1, 3일 때 남자

2, 4일 때 여자


중간 글자 바꾸기

=REPLACE(데이터,시작,몇개,바꾸려는문자)

=REPLACE(B3,9,6,"******")


특정 텍스트 변경

=SUBSTITUTE(데이터,"바꾸고 싶은 문자","바꿀 문자")

=SUBSTITUTE(B4,"-","")

B4의 -를 없애기


해당 행/열에 해당하는 값 찾기

=INDEX(범위,행번호,열번호)

=INDEX(C4:E8,3,2)

C4:E8 범위 안에서 3행 2열의 데이터 값 추출


범위 안에 특정 행/열 알아내기

=MATCH(값,범위,0,-1,1적기)

=MATCH(MAX(F3:F14),F3:F14,0)

범위 안에 가장 큰 값이 있는 행 알아내기




index -> 범위 안에서 해당 행/렬에 있는 값 구하기

index(범위, 행, 렬)


match -> 범위 안에서 특정 값 구하기(디폴트: 0)

match(특정 값, 범위, 0)


small -> 범위 안에서 가장 작은 값 구하기

lm(mpg~hp, data=mtcars)

# y = ax + b

# intercept가 a

# hp가 b

# 즉, y = 30.09 - 0.06x


DF<-data.frame(Work_hour=1:7, Total_pay=seq(10000, 70000, by=10000))


# Work_hour = X 변수 ; Total_pay = Y 변수

plot(Total_pay ~ Work_hour, data=DF, pch=20, col="red") # pch는 점 모양

grid()


LR<-lm(Total_pay ~ Work_hour, data=DF) # 종속~독립변수

mode(LR)

names(LR)


grid()

abline(LR, col="blue", lwd=2) # lwd는 선 굵기

# 기하분포


# 20%의 성공확률이 5번 째에 성공할 확률 

a<-dgeom(1:5, 0.2)

a


# 20%의 성공확률을 5번 시행하는 동안에 성공할 확률(누적)

sum(a[1:5])



# X가 0에서 시작할 때 -> X번 실패하고 처음으로 성공할 확률

# X가 1에서 시작할 때 -> X번 째에 성공할 확률

'programing > R studio' 카테고리의 다른 글

시계열 분석 예제  (0) 2018.07.29
회귀분석 - lm  (0) 2018.07.02
ggplot2 - scale_x_discrete, scale_y_discrete - x, y값 순서 정렬  (0) 2018.06.29
createDataPartition() - 층화 균등 추출  (0) 2018.06.26
dcast()  (0) 2018.06.26

scale_x_discrete, scale_y_discrete - x, y값 순서 정렬


ex)

ggplot() + ... +

scale_x_discrete(limit=c("a", "b", "c")

'programing > R studio' 카테고리의 다른 글

회귀분석 - lm  (0) 2018.07.02
기하분포 - dgeom  (0) 2018.07.02
createDataPartition() - 층화 균등 추출  (0) 2018.06.26
dcast()  (0) 2018.06.26
정규화란?  (0) 2018.06.25

+ Recent posts