STUDY/R

R_RStudio(IDE)_학습하기(3)

oort2 2023. 2. 13. 08:54

이번에는 데이터 전처리에 대해 학습했다. 

전처리를 한 후 필요한 내용만 데이터를 출력해서 사용하면 된다. 

 

*for문으로 행 정렬하기 

# 응시자 10명의 점수를 가지고, 응시자의 합격 여부 판단하기
s1 <- c(14,16,12,20,8,6,12,18,16,10)
s2 <- c(18,14,14,16,10,12,10,20,14,14)
s3 <- c(44,38,30,48,42,50,36,52,54,32)
score<-data.frame(s1,s2,s3)
score
#응시자별 과목별 총점을 출력하기
total<-apply(score,1,sum)
total
#crl+f ->같은 단어 찾기 
scoreset<-cbind(score, total)
scoreset

result<-c()
for(i in 1:nrow(scoreset)){
  if(scoreset[i,1]<20*0.4 | scoreset[i,2]<20*0.4 | scoreset[i,3]<60*0.4){
    result[i]<-'불합격'
  }else if(scoreset[i,4]>=60){
    result[i]<-'합격'
  }else{
    result[i]<-'불합격'
  }
  cat(i,'번째 응시생:',result[i],'\n')
}
result
scoreset<-cbind(score, result) #행추가
scoreset

scoreset[,1:3]
#과목별 평균
apply(scoreset[,1:3],2,mean)
#과목별 총점
apply(scoreset[,1:3],2,sum)
#과목별 범위
apply(scoreset[,1:3],2,range)
#과목별 분산
apply(scoreset[,1:3],2,var)
#과목별 표준편차
apply(scoreset[,1:3],2,sd)

*which문으로 조건에 맞는 데이터의 위치 찾기 

############### 조건에 맞는 데이터의 위치 찾기 ##############
# which(조건)         : 조건 맞는 데이터의 위치 리턴 
# which.max(데이터셋) : 데이터셋에서 최대값의 위치 리턴
# which.min(데이터셋) : 데이터셋에서 최소값의 위치 리턴
#############################################################
score<-c(76,84,69,50,95,60,82,71,88,84)
# 성적이 69인 학생은 몇번째?
which(score==69)
# 성적이 85점 이상인 학생은 몇번째?
which(score>=85)
# 성적이 가장 높은 성적은?
which.max(score)
# 성적이 가장 낮은 성적은?
which.min(score)

*막대그래프 작성하기

f <- c('WINTER','SUMMBER','SPRING','SUMMBER','SUMMBER',
       'FALL','FALL','SUMMBER','SPRING','SPRING')
f
ds<-table(f)
ds

barplot(ds, main='favorite season')
#막대그래프에 색상추가
color<-c('blue','red','green','yellow','turquoise1')
barplot(ds, main='favorite season', col=color)
#x,y축에 설명
barplot(ds, main='favorite season', col=rainbow(5), xlab='계절',ylab='빈도수')
#가로형태로 표시
barplot(ds, main='favorite season', col=rainbow(5), horiz=TRUE, las=1)
#이름 변경하기
barplot(ds, main='favorite season', col=rainbow(5), horiz=TRUE, names=c('F','SP','SU','W','AA'))

#X축의 이름을 새로 표시
barplot(ds, main='favorite season', col=rainbow(5), las=1)
#las=0 : 기본값, 축방향
#las=1 : 수평방향
#las=2 : 축의 수직방향
#las=3 : 수직방향

#막대 그래프에 그룹별 따로 표현. 범례 추가하기. 범례의 위치지정.
#bty='o' : 기본값. 테두리 표시
#bty='n' : 테두리 표시안함
#inset=(x,y) : 범례를 x,y축 이동값. -1 ~ 1사이의 값.
#              -0.25 : 25% 반대방향으로 이동
# x='topright' : 범례 표시의 위치. 오른쪽위
barplot(ds, main='인구추정', col=c('red','blue','yellow')
        , beside = TRUE, legend.text = T,
        args.legend = list(x='topright',bty='n',inset=c(0,2,0,2)))

# par : 그래프를 표시할 창을 설정.
# mfrow=c(1,1) : 그래프를 그릴 창의 갯수를 행과 열로 표시. 
#                그래프를 그릴 화면 분할.
# mar=c(5,5,5,7) : bottom,left,top,right 여부를 부여.
par(mfrow=c(1,1), mar=c(5,5,5,7))
barplot(ds, main='인구추정', col=c('red','blue','yellow')
        , beside = TRUE, legend.text = T,
        args.legend = list(x='topright',bty='n',inset=c(-0.25,0)))
ds
#범례의 표시되는 내용을 변경.
barplot(ds, main='인구추정', col=c('red','blue','yellow')
        , beside = TRUE, legend.text = c('0~14세','15~64세','65세이상'),
        args.legend = list(x='topright',bty='n',inset=c(-0.25,0)))

#열의 이름 설정하기
colnames(ds)<-c('19.1Q','19.2Q','19.3Q','19.4Q','20.1Q')
ds

*히스토그램으로 그래프 만들기(막대보다 간단)

############### 히스토 그램 ####################
# 수치형 자료의 분포의의 시각화시 사용되는 그래프
# hist() : 히스토그램 그래프 표시
################################################
head(cars)
str(cars)
dist<-cars[,2]
dist
#그동안은 우리가 묶었는데, 얘는 지가 알아서 그래프 만들어줌
hist(dist) # 히스토그램 출력
hist(dist, breaks=12) # 히스토그램 출력

hist(dist, #데이터 수치형 데이터.
     main = 'Histogram for 제동거리', #제목
     xlab='제동거리' , #x축설명
     ylab = '빈도수', #y축 설명
     border='blue', #테두리 색상
     col='green', #막대의 색상
     las=2, #0~3, x축의 글씨 방향지정
     breaks = 5 # 구간분리
     )

h<-hist(dist, main='Histogram for 제동거리', breaks=6)
h #histogram 그래프 출력을 위해 사용된 데이터 정보
class(h)
h$breaks # 히스토그램의 구간 값.
h$counts # 구간의 갯수, 빈도수, 막대그래프의 크기.
h$density # 밀도
h$mids #중간값
h$name #데이터 이름
h$equidist #그래프 간격의 크기가 일정한지 여부

freq<-h$counts
freq
#h$breaks[-1] : 1번째 요소 제외하고...
names(freq)<-h$breaks[-1] 
freq
#히스토그램에 빈도수 표시
#text(x좌표, y좌표, 표시할 값, 정렬방식)
#adj(가로, 세로): -1~1사이 값
#  0: 오른쪽 정렬, 0.5 가운데, 1: 왼쪽 정렬
#  0: 위쪽, 0.5 가운데, 1:아래쪽:-0.5
text(h$mids, h$counts, labels = h$counts, adj=c(0.5, -0.5))

*원형그래프 만들기

################# pie 그래프 ############
f <- c('w','su','sp','su','su','f','f','su','sp','sp')
f
#도수분포
ds<-table(f)
ds
pie(ds,main='선호계절')
barplot(ds, main='선호계절')

#색상지정하기
pie(ds,main='선호계절', col=rainbow(length(ds)))

*3D그래프

#3d 그래프 그리기
install.packages('plotrix')
library(plotrix)
#labelcex=1 : 출력되는 글자의 크기 지정. 0.5 크기가 반.
#explode=0.1: 부채꼴의 간격
pie3D(ds, main='선호계절', labels=names(ds), lablescex=1, explode=0.1,
      col=rainbow(4))

*선그래프

######### 선그래프 ########
# plot(x축데이터,y축데이터,...)
# 시간의 변화에 따른 데이터의 시각화에 주로 사용되는 그래프 
###########################

#월별 지각생의 수
month<-1:12
late<-c(5,8,7,9,4,6,12,13,8,6,6,4)
#type: (1,b,s,o)
#lty = 1~6 : 선의 종류
#lwd=1 : 선의 굵기
plot(month, late, type='b', lty=6,lwd=2,xlab='Month',ylab='Late cnt')

late2<-c(4,6,5,8,7,8,10,11,6,5,7,3)
plot(month, late, main='Late Students', type='b', lty=1, lwd=1, xlab='Month',
     ylab='Late cnt', col='red')
#lines 함수를 이용하여 선을 추가하기
lines(month, late2, type='b', col='blue')

*산점그래프

########## 산점도 ######
# 두변수사이의 관계 파악에 사용되는 그래프
# 다중변수 데이터에서 사용됨.

plot(mtcars$wt, mtcars$mpg, main='중량-연비 그래프',
     xlab='중량', ylab='연비(mpg)',
     col='red',pch=20)
#pch=19 : 점의 형태

# 여러 변수들 간의 산점도
vars <-c('mpg', 'disp', 'drat','wt'  )
str(mtcars)
target<-mtcars[,vars]
target
plot(target, main='여러변수들 간의 산점도')

str(iris)