반응형

R studio에 속성 관리자권한으로 체크해야 권한이 없다고 안 뜬다.

 

dplyr 패키지를 이용한  데이터 전처리

dplyr 로 가공하기

 

airquality->자동완성

 

dplyr

 

obs 행-> 관측칙
variables 변수  독립변수
variables object

 

dim(airquality)
summary(airquality)
str(airquality)

#airquality를 이름바꾸기
air <- airquality
air

summary(air)
str(air)

a = 1
a

 

airquality 를 덥어썼으면 끄고 다시시작하기 기본으로 주는 것은 수정할 수 없다.메모리상에서 객체만 존재

 

#dplyr설치
install.packages("dplyr")
library(dplyr)

 

#dependency 필요한것도 같이 가져와서 설치

glimpse()#

str(air)
glimpse(air)#str q보다 직관적이게 보일수 있다.

 

# air에서 month하고 day로 
air1 <- air[,c(5,6)]
air1

air1 <- air[,c(1,3)]
air1

air1 <- air[,c('Ozone','Wind')]
air1

air1 <- air[,c('Ozone','Wind')]
head(air1)

tail(air1)

#1행부터 20행 까지 
air1 <- air[1:20,]
air1

air1 <- air[,1:4]
air1

air1 <- air[,c(-5,-6)]
air1

colnames(air1)# head이름  열
rownames(air1) #row 이름  행
names(air1)#열이 더 중요하다. 

엑셀보다   csv읽는 이유는 크기가 작아서 
rep->복제 

 

x1 <- 1:20
x2 <- rep(c("a","b"),10)
x2
x3 <- sample(1:200,20) #random 데이터 
x3

 

# 1-50  random 10개
x1 <- sample(1:50,10) #random 데이터 
x1
# 1은 안쓰도  default로 되여있다.
x1 <- sample(50,10) #random 데이터 
x1
# 30-50  random 10개
x1 <- sample(30:50,10) #random 데이터 
x1
# 45-50  random 10개
x1 <- sample(45:50,10,replace = TRUE) #'replace = FALSE' 일때는 모집단보다 큰 샘플을 가질 수 없습니다
x1
# 45-50  random 10개
x1 <- sample(45:50,10,replace = TRUE) #random 데이터 뽑는 것 또 뽑는다. 복원추측

 

x1 <- sample(45:50,10,replace = TRUE) #random 데이터 뽑는 것 또 뽑는다. 복원추측 
x1

set.seed(1234)

x1 <- sample(45:50,10,replace = TRUE) #set.seed하고 조회

x1

 

#airquality에서 153개인데 random으로 15개 끄내기
ari1 <- airquality
index <- sample(153,15)
index
air1 <- air1[index,]
air1

 

air1 <- nrow(airquality)
air1
air1 <- ncol(airquality)
air1

 

index <- sample(nrow(airquality),15)
index

 

vector한개  set안에 여러개 연다.

air1 <- airquality
air1
a <- sample(nrow(air1),15)
a[3]# 3번쨰 것 꺼내기 
dim(air1)[1]

#alt+-누르면 된다. <-

#153개 중에서 70%만큰 샘플링으로 나온다.
index1 <- sample(nrow(air1),nrow(air1)*0.7) 
index1
train <- air1[index,]
test <- air1[-index,]

 

 

ls()
rm(air)
rm(a,A)
ls()
rm(list = ls())->모두 지우기

 

R
help(sample)
prob  a vector of probability weights for obtaining the elements of the vector being sampled. 비율
?sample help와 가능이 같다.

 

RStudio f1

head

 

dplyr 패키지를 이용한  데이터 전처리 \
filter(  ) 행 추출 
select(  ) 열(변수) 추출 
arrange(  ) 정렬 
mutate(  ) 변수 추가 
summarise(  ) 통계치 산출 
group_by(  ) 집단별로 나누기 
left_join(  ) 데이터 합치기(열) 
bind_rows(  ) 데이터 합치기(행) 

 

filter 조건 class가 열 
%>% -> ctrl+shift+m %>% 파이프 연산자  Ctrl + Shift + M

 

library(dplyr)
exam <- read.csv("csv_exam.csv")
exam

exam %>% filter(class == 1)# class가 1인것 
exam %>% filter(class != 1)
exam %>% filter(math > 50)#수학점수가 50보다 크다.
exam %>% filter(english >= 80)
exam %>% filter(class == 1 & math >= 50)

exam %>% filter(class == 1 | english >= 90)

exam %>% filter(class == 1 | class == 3 | class == 5)
exam %>% filter(class %in% c(1,3,5))

class1 <- exam %>% filter(class==1)
mean(class1$math)
air <- airquality
air
air %>% filter(Day>20)#20보다 큰 달을 구한다.
air %>% filter(Day>20) %>% filter(Month == 9)
# 1,3 반중에서 80명 이상되는 분 
exam %>% filter( (class == 1 | class == 3) & english >= 80 ) 

#열 추출
exam %>% select(math)
exam$math

exam %>% select(class,math,english)
select(exam, class)#열의 이름을 가져온다.위에것과 같은 원리이다.

exam %>% select(-math)

가독성을 위해서,
%>%(파이프 연산자)에서 줄을 바꾼다.
Enter를 치면 알아서 들여쓰기가 된다.

 

# class가 1인 english 열만 
exam %>% filter(class == 1) %>% select(english)
exam %>% select(english) %>% filter(class == 1)
#atomic과 리스트 타입들에 대해서만 비교(1)가 가능합니다
#같아 보이는데 조금 다르다.

가독성을 위해서,  %>%(파이프 연산자)에서 줄을 바꾼다. 
 
Enter를 치면 알아서 들여쓰기가 된다. 

dplyr 로 가공하기 

 

exam %>% arrange(math)#order by 오름차순
exam %>% arrange(desc(math))#내림 차순

exam %>% arrange(class,math) # 1순위 class 2순위 math


4. 파생변수 추가하기 & 집단별로 요약하기 
4. 파생변수 추가하기 ->앞의 것에서 열의 의하여 새로운 열을 만든다.
mutate->있는데서 변형하는 것이다.
exam %>% mutate(total = math+english+science) %>% 
  head

exam

 

exam %>% mutate(total = math+english+science,
                mean = (math+english+science)/3) %>% 
        head

exam %>% mutate(test = ifelse(science >= 60),"pass","fial") %>% 
         head 

exam %>% mutate(total = math+ english+science) %>% 
        arrange(total) %>% 
        head

 

요약 통계량 함수

mean(  ) 평균 ->r전체에서
sd(  ) 표준편차 ->r전체에서
sum(  ) 합계 ->r전체에서
median(  ) 중앙값 ->r전체에서
min(  ) 최솟값 ->r전체에서
max(  ) 최댓값 ->r전체에서 
n(  ) 빈도 ->summarize만 같이 있을때만 작동한다.

 

summarise( ): 

summarise() is typically used on grouped data created by group_by().

The output will have one row for each group

summarise(data.frame, functions...) 

수치형 값에 대한 "요약" 통계량을 계산하여 출력한다. 
Center: mean(), median() 
 Spread: sd(), IQR(), mad() 
Range: min(), max(), quantile() 
Position: first(), last(), nth(), 

 

exam %>% summarise(mean_math = mean(math))# 수학평균이 얼마인가

exam %>% 
   group_by(class) %>% 
   summarise(mean_math = mean(math))

exam %>% 
  group_by(class) %>% 
  summarise(sd_math = sd(math))

#class별로 평균하였을 경우 
exam %>% 
  group_by(class) %>% 
  summarise(mean_math = mean(math),
            sum_math = sum(math),
            median_math = median(math),
            n = n()) #학생수 

mpg %>% 
  group_by(manufacturer) %>% 
  filter(class == "suv") %>% 
  mutate(tot = (city+hwy)/2) %>% 
  summarise(mean_tot = mean(tot)) %>% 
  arrange(desc(mean_tot)) %>% 
  head(5)

 

R을 활용한 Data Visualizaition

2일차 데이터 시각화 / 전처리

데이터 시각화 / 전처리 
1. 데이터 시각화의 중요
2.  기본 그래픽- 고수준, 저수준 
R 그래픽 도구 
1.  R 기본 그래픽  (R Base Graphics) 
2.  Lattice Graphics 
3.  ggplot2 
Easy    Fast   Beautiful 
1.  R 기본 그래픽  (R Base Graphics) 
내장되여있어서 설치 필요없음
막대그래프, 히스토그램, 파이그래프 등 여러 시각화 방법을 제공 

별도의 설치 및 호출 필요 없고 가벼움     
설정이 다소 복잡하고 아름답지 못하다는 단점 

 

2.  lattice 
한꺼번에 많은 플롯을 생성할 수 있다.  
다차원의 데이터를 사용하여 변수들갂의 관계를 살펴보는데 유리  
순차적으로 그래프 쌓아가는 것이 어려워 직관적이지 못하다 

 

3.  ggplot2 
이전 두 패키지(R Base Graphics, Lattice Graphics)의 장점만 모아 둔 패키지 
 
갂단한 그래프 문법 + 아름다운 고급그래프 + 레이어로 쌓아감 
 
데이터객체, 그래픽객체로 나눌 수 있어 코드의 재사용성이 높다. 

 

Anscombe’s  quartet 

이산변수 점수 단위로 나누어 측정할 수 있는 변수 막대차트,점그패프,원 차트 등을 이용하여 시각화하면 효과적 
연속변수 시간,길이 등 

고수준 그래픽 함수(high level graphic functions) 
 

plot 함수 
데이트를 x-y평면 상에 출력하는 함수

plot(x, y, type = ‘type value’, main=‘title’, col=color) 
# type : plot의 형태로 점, 선 등을 선택할 수 있다. 
# main: 그래프의 제목 설정 
# col : 그래프의 색상 
Type 옵션 
p : 점(points),  l : 선(lines),  b : 점과 선(both points and lines),  c : b옵션에서 점이 빠짂 모습, 
o : 겹친 점과 선(overplotted),  h : 수직선 ,  s : 수평선 우선의 계단 모양 (steps), 
S : 수직선 우선의 계단 모양 (steps),  n : 배경맊 그리고 출력하지는 않음 (no plotting)  

 

mtcars#r자체에 내장되여있다.
?mtcars
str(mtcars)
names(mtcars)

plot(mtcars)
attach(mtcars)

wt
plot(wt)
mpg
plot(wt, mpg)
plot(wt, mpg, main = "wt와 mpg의 관계")
plot(wt, disp, mpg)#

install.packages("scatterplot3d")
library(scatterplot3d) #package ‘scatterplot3’ is not available (for R version 3.6.1)

scatterplot3d(wt, disp, mpg, pch = 16, main="3D Scatter Plot")
scatterplot3d(wt, disp, mpg, pch = 16, highlight.ed= TRUE, type ="h" , main="3D Scatter Plot")

install.packages("rgl")
library(rgl)
plot3d(wt, disp, mpg)
plot3d(wt, disp, mpg, main="wt Vs mpg Vs disp", col ="red", size="10")

고수준 그래픽 함수(high level graphic functions)

plot() 산점도 출력
barplot() 막대 차트 출력
pie() 파이 차트 출력
matplot() 다중 산점도 출력

 

x11() 

par(mfrow= c(2,3))#multifrow 6개 분할 

plot(0:6,0:6, main ="default")
plot(0:6,0:6, type="b" , main="type = \"b\"")
plot(0:6,0:6, type ="c", main="type =  \"c\"")
plot(0:6,0:6, type ="o", main="type = \"o\"")
plot(0:6,0:6, type="s", main="type= \"s\"")
plot(0:6,0:6, type="S", main="type= \"S\"")

범주형 데이터의 수준별
사용법 barplot(H, width = 1, beside = FALSE, main=‘title’, col=NULL, horiz= …) 

# H (height): 백터나 행렧 입력 가능 (당연히 numeric) 
# beside 인수 : 옆으로 나란히. FALSE 는 누적 
# col : 그래프의 색상 
# horiz= 막대를 평행하게

par(mfrow=c(1,1))
x <- c(38,52,24,8,3)
barplot(x) 막대그래프

par(mfrow=c(1,1))
x <- c(38,52,24,8,3)
barplot(x)

names(x) <- c("Excellent","Very Good","Good", "Fair","Poor")
barplot(x)

y <- scan()
1:  1 2 3 3 4 3 4 1 5 3 3 3 2 4 4
16: 2 4 3 5 3 1 2 3 3 4 4 3 2 3 4
barplot(y)

par(mar=c(2,4,2,2))#여백주는 함수
barplot(table(y), xlab= "Beverage", ylab ="Frequency")
barplot(table(y)/length(y), xlab ="Beverage", ylab = "proportion")
table(y) : 데이터의 도수를 표현 length(y) : 데이터의 갯수(길이) 

객체만들기
sales <- c( 45, 44, 46)
names(sales) <- c("Park", "Kim" ,"Lee")
barplot(sales, main="Sales", ylab ="Thousands")
sales: 데이터 객체 names(sales) : 데이터의 이름 설 정 

범위 조절하기
barplot(sales, main="Sales", ylab ="Thousands" , ylim=c(42,46), xpd=FALSE)
ylim = c(42,46) : y 축 범위 설정 xpd=FALSE : 막대의 벖어남 허용여 부 

pie차트
x
pie(x)

 

names(x) <- c("Excellent","Very Good", "Good","Fair","Poor")
barplot(x)
barplot(x, xlab="수준",ylab="점수")
barplot(x, xlab="수준",ylab="점수", col="blue")
barplot(x, xlab="수준",ylab="점수", col="blue", horiz=TRUE)#범위가 40에서 나갔다.
barplot( x, xlab="수준" , ylab = "점수" , col=c("blue","light blue","red","yellow","grey"), horiz=TRUE)#범위

pie함수
데이터를 파이 차트(원 그래프)로 출력하는 함수

사용법 pie(x, labels = names(x), radius = 0.8, clockwise = FALSE, init.angle = if(clockwise) 90 else 0, density = NULL, angle = 45, col = NULL, …) 

# x : 음수나 0이 아닌 숫자형 벡터  

# labels : 기본값으로 x 벡터의 이름이 사용, 새롭게 지정 가능 

# radius : 파이의 반지름 
# init.angle : 파이 차트가 시작되는 각도(clockwise가 TRUE면 90도 아니면 0도 ) 
# density : 파이 내부의 빗금을 표시하는 밀도 
# angle : 파이 내부의 빗금으 표시하는 기울기 
# col : 파이 내부의 색상 

score <- read.table("score.txt",header= T ,fileEncoding = "UTF-8")
score

score$"성명"

score$"국어"

paste(score$"성명","-",score$"국어")

pie(score$"국어", lables = paste(score$"성명","-",score$"국어"),col=rainbow(10),clockwise=TRUE)

pie(score$"국어", lables = paste(score$"성명","\n","(",score$"국어",")"),col= rainbow(10), clockwise=TRUE)        

install.packages("googleVis")
library(googleVis)

buildcolors <- function(color_count){
  colors <- rainbow(color_count)
  colors <- substring(colors,1,7)
  colors <- paste(colors,collapse = "','")
  colors <- paste("'",colors,"'",sep="")
  colors <- paste("[",colors,"]",sep ="")
  return(colors)
}

cols <- buildcolors(10)

pie <- gvisPieChart(data.frame(score$'성명',score$'국어'),option = list(width = 600, height = 600, title='국어성적',colors=cols,pieSliceText ="label",pieHole="0.5"),chartid="donut")
header <- pie$html$header
header <- gsub("charset=utf-8","charset=euc-kr",header)
pie$html$header <- header
plot(pie)

pie <- gvisPieChart(data.frame(score$"성명",score$"국어"),option = list(width = 600, height = 600, title="국어성적",colors=cols,pieSliceText ="value",pieHole="0.5"),chartid="donut")
header <- pie$html$header
header <- gsub("charset=utf-8","charset=euc-kr",header)
pie$html$header <- header
plot(pie)

paste() : 문자열을 붙이는 함수
clockwise = TRUE : 파이 차트 시작각도 를 90도로 설정

 

\n : 줄바꿈

 

저수준 그래픽 함수(low level graphic functions) 
points() 지정핚 좌표에 점을 찍는 함수 
abline() y=a+bx 의 직선을 그리는 함수 
legend() 범례를 출력하는 함수 
text() 
Plot 영역의 (x,y) 좌표에 문자 를 출력하는 함수 

 

Ex) abline(a, b, lty, col, other options) # y = a + bx abline(h = a, lty, col, other options) # y = a abline(v = b, lty, col, other options) # x = b abline(lm object) # 회귀 직선 
 
# lty : line type으로 1-solid line, 2-dashed line 등 # col : 직선의 색상 

 

cars
cars[1:4,]

#값을 예측하기 위해서 하는 것 
z <- lm( dist ~ speed, data = cars)
summary(z)

x11()
par(mfrow= c(1,1))
plot(cars,main ="abline")


abline(h = 20)
abline(h = 30)

abline(v = 20, col ="blue")

abline(a = 40, b = 4, col='red')

abline(z, lty= 2, lwd= 2, col= 'green')

abline(z$coef, lty= 3, lwd = 2, col='red')

legend()함수

legend(x, y, legend, pch, lty, fill, col, …) x, y : legend를 출력할 위치 지정  ex) x=a, y=b : 좌표 (a,b) 에 범례를 출력 위치를 나타내는 문자사용 ex) ‚topright‛, ‚bottomleft‛, ‚center‛ 등 
 
pch : 점에 대한 범례일 경우, 점을 구분하기 위해 사용 

lty : 선에 대한 범례일 경우, 선의 type을 구분하기 위해 사용 

fill : 면에 대한 범례일 경우, 면의 색상을 구분하기 위해 사용 

pch와 lty 동시 사용 : 점과 선을 동시에 사용한 그래프의 범례 

x11()
plot(1:10, type="n", xlab="",ylab="",main="legend")

legend("bottomright","(x,y)",pch=1,title="bottomright")
legend("bottom","(x,y)",pch=1,title="bottom")
legend("bottomleft","(x,y)",pch=1,title="bottomleft")
legend("left","(x,y)",pch=1,title="left")
legend("topleft","(x,y)",pch=1,title="topleft")
legend("top","(x,y)",pch=1,title="top")
legend("topright","(x,y)",pch=1,title="topright")
legend("right","(x,y)",pch=1,title="right")
legend("center","(x,y)",pch=1,title="center")
legends <- c("Legend1","Legend2")

legend(3,8, legend= legends,pch = 1:2, col = 1:2)
legend(7,8, legend= legends,pch = 1:2, col = 1:2,lty= 1:2)
legend(3,4, legend= legends,fill = 1:2)
legend(7,4, legend= legends,fill = 1:2, density = 30)

연습문제:

x <- c(1,1,1,2,2,2,2,2,2,3,3,4,5,6)
y <- c(2,1,4,2,3,2,2,2,2,2,1,1,1,1)
zz <- data.frame(x,y)
zz
sunflowerplot(zz)
plot(zz)

data(mtcars)
stars(mtcars[,1:4])
stars(mtcars[1:4], flip.labels= FALSE, key.loc = c(13,1.5))

stars(mtcars[1:4], key.loc = c(13,1.5), draw.segments = TRUE)

xx <- c(1,2,3,4,5)
yy <- c(2,3,4,5,6)
zz <- c(10,5,100,20,10)
symbols(xx,yy,xx)

xx <- c(1,2,3,4,5)
yy <- c(20,13,40,50,60)
zz <- c(10,5,100,20,10)
c <- matrix(c(xx,yy,xx),5,3)
c
pairs(c)#컬럼수가 많고 수치형이고 범주형이 그만큼 많을때 

 

persp()#3차원함수

contour()#3차원함수
filled.contour(volcano,color.palette = terrain.colors,asp=1)
title(main="volcano data: filled contour map")

plot(0:6,0:6, type="n", main="type= \"n\"")
plot(0:6,0:6, type="b", lty="dashed")

x <- runif(100)
y <- runif(100)
plot(x,y,pch = ifelse(y > 0.5, 1,18)) #pointcharacter

plot(x,y ,pch = ifelse( y >0.6, 15, ifelse( y > 0.4, 5, 14)))

plot(x,y ,pch = ifelse( y >= 0.7 , 8, ifelse( y>= 0.5, 5, ifelse(y >= 0, 12))))
#kbo.csv ㅇ읽어서 
kbo <- read.csv("kbo.csv")
kbo
#6행보여주기
head(kbo)

#팀별로 정렬하되 알파벳 내림차순 6행까지 출력
kbo %>% group_by(팀) %>% arrange(desc(팀)) %>% head() 

arrange(kbo,desc(팀)) %>% head()

#2017년도의 것만 추출하며 첫 6행 까지 출력하세요 
filter(kbo,연도 == 2017) %>% head()

kbo

#안타,2루타 ,3루타,홈런만 추출하여 첫 6행 까지 출력하세요
select(kbo,안타,X2루타,X3루타,홈런) %>% head()

#2017년도 안타,2루타 ,3루타,홈런첫 5행까지 
filter(kbo,연도 == 2017) %>%  select(  X2루타,X3루타,홈런)%>%   head(5)

kbo

#데이터를 타율(안타/타수)이라는 변수를 넣고 첫 6행 까지 출력하세요 
kbo %>% mutate(타율 = 안타/타수) %>% head()
mutate(kbo, 타율 = 안타/ 타수) %>%  head()
반응형

'Study > R' 카테고리의 다른 글

R-6  (0) 2020.09.05
R-5  (0) 2020.09.05
R-4  (0) 2020.09.05
R-3  (0) 2020.09.05
R-1  (0) 2020.09.02

+ Recent posts