인공지능 수업(R)

인공지능 6/9 R 차례_13

TalleQQ 2021. 6. 9. 17:47

#R

#인공지능

 

#서대문구에 치킨집이 많은 동은?
install.packages("readxl")
library(readxl)

ck <- read_xlsx("치킨집_가공.xlsx")
head(ck)

#substr() 함수를 이용하여 소재지전체주소에 있는 11~15번째 문자 가져오기
addr <- substr(ck$소재지전체주소, 12, 16)

head(addr)

addr_num <- gsub("[0-9]", "", addr) #숫자제거
addr_trim <- gsub(" ", "", addr_num) #공백제거

head(addr_trim)

install.packages("dplyr")
library(dplyr)

#table() 함수를 이용해서 숫자 세기, 변수가 한개일때 도수분표표를 만들어줌
addr_count <- addr_trim %>% table() %>% data.frame()
head(addr_count)

install.packages("treemap")
library(treemap)

#treemap(데이터, index=인덱스 표시 열 제목, vSize=크기를 이용할 열 제목, vColor=컬러, title=제목)
treemap(addr_count, index=".", vSize="Freq", title="서대문구 동별 치킨집 분표")

arrange(addr_count,desc(Freq)) %>% head()

치킨집_가공.xlsx
0.05MB

 

 

#Project 02 지역별 미세먼지 농도 비교하기

install.packages("readxl") # readxl 패키지 설치 
install.packages("dplyr") # dplyr 패키지 설치

library(readxl) # readxl 패키지 로드

# dustdata.xlsx 파일을 불러온 후 dustdata_anal에 할당
dustdata <- read_excel("dustdata.xlsx")

View(dustdata) # 데이터 확인
str(dustdata) # 데이터 속성 확인

library(dplyr) # dplyr 패키지 로드

# 성북구와 중구 데이터만 추출 및 확인
dustdata_anal <- dustdata %>% filter(area %in% c("성북구", "중구")) 

View(dustdata_anal)

# dustdata_anal 데이터 세트에 yyyymmdd에 따른 데이터 수 파악
count(dustdata_anal, yyyymmdd) %>% arrange(desc(n))

# dustdata_anal 데이터 세트에 area에 따른 데이터 수 파악
count(dustdata_anal, area) %>% arrange(desc(n))

# area 값이 성북구인 데이터를 dust_anal_area_sb에 할당
dust_anal_area_sb <- subset(dustdata_anal, area == "성북구") 

# area 값이 중구인 데이터를 dust_anal_area_jg에 할당
dust_anal_area_jg <- subset(dustdata_anal, area == "중구")

# 데이터 확인
dust_anal_area_sb 
dust_anal_area_jg

# psych 패키지 설치 및 로드
install.packages("psych")
library(psych)

# 성북구의 미세먼지량에 대한 기초 통계량 도출
describe(dust_anal_area_sb$finedust)

# 중구의 미세먼지량에 대한 기초 통계량 도출
describe(dust_anal_area_jg$finedust)

par("mar")
par(mar=c(1,1,1,1))

# 성북구와 중구의 미세먼지 농도에 대해 boxplot을 통한 분포 차이 확인
boxplot(dust_anal_area_sb$finedust, dust_anal_area_jg$finedust,
        main = "finedust_compare", xlab = "AREA", names = c("성북구", "중구"), 
        ylab = "FINEDUST_PM", col = c("blue", "green"))

# dustdata_anal 데이터 세트에서 측정소명(area)에 따라 미세먼지 농도 평균에 대한 차이를 검증
t.test(data = dustdata_anal, finedust ~ area, var.equal = T)

dustdata.xlsx
0.06MB

#### 13-2 ####

## -------------------------------------------------------------------- ##
library(ggplot2)
mpg <- as.data.frame(ggplot2::mpg)

library(dplyr)
mpg_diff <- mpg %>% 
  select(class, cty) %>% 
  filter(class %in% c("compact", "suv"))

head(mpg_diff)
table(mpg_diff$class)

t.test(data = mpg_diff, cty ~ class, var.equal = T)


## -------------------------------------------------------------------- ##
mpg_diff2 <- mpg %>% 
  select(fl, cty) %>% 
  filter(fl %in% c("r", "p"))  # r:regular, p:premium

table(mpg_diff2$fl)

t.test(data = mpg_diff2, cty ~ fl, var.equal = T)

#### 13-3 ####
library(ggplot2)
## -------------------------------------------------------------------- ##
economics <- as.data.frame(ggplot2::economics)
cor.test(economics$unemploy, economics$pce)


## -------------------------------------------------------------------- ##
head(mtcars)
car_cor <- cor(mtcars)  # 상관행렬 생성
round(car_cor, 2)       # 소수점 셋째 자리에서 반올림해서 출력

install.packages("corrplot")
library(corrplot)

corrplot(car_cor)

corrplot(car_cor, method = "number")

col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))

corrplot(car_cor,
         method = "color",       # 색깔로 표현
         col = col(200),         # 색상 200개 선정
         type = "lower",         # 왼쪽 아래 행렬만 표시
         order = "hclust",       # 유사한 상관계수끼리 군집화
         addCoef.col = "black",  # 상관계수 색깔
         tl.col = "black",       # 변수명 색깔
         tl.srt = 45,            # 변수명 45도 기울임
         diag = F)               # 대각 행렬 제외


install.packages("twitteR")
install.packages("ROAuth")

library(twitteR)
library(ROAuth)


library(twitteR) # 패키지 로드

#접속시 입력해야 하는 정보 예
#consumerKey = "0iApiCFYRk2VLXPvquUTvRj67"
#consumerSecret = "UCxXRCpPUBzcLEGqK0R1XhHo9aS2cC6goKm52sRy5p316EBMg4"
#accessToken = "74414052-7DLWvzEEVHhGqnfUhr6U4ioEc74oA0pQCpLFsPvhj"
#accessTokenSecret = "31FhCeVp7selgZxTdSJ6O6GpXSv5c6G7WypjjYDBwjxpD"

a = "4OGxbiGE8Z3tXWA9pSRsks7SC"
b = "izX15KJgzuWsi1XdgklrsQRqVz9qTVZWYdwE7z8JkV27psaE4Y"
c = "71181251-KSVuiSbLgF6IGsoePsZhqCI7kXvoLEo83Swgtxqam"
d = "trXrZaUrLldIQs7WyRH4MtCQnGEcKZxHtP93RR4ZKLjpf"
setup_twitter_oauth(a, b, c, d)

keyword <-enc2utf8("월드컵") #한글로 데이터형 변환
bigdata <- searchTwitter(keyword, n=100, lang="ko") #한국어 100개 크롤링
head(bigdata)


#감성 분석 함수
score.sentiment = function(sentences, pos.words, neg.words)
{
  scores = laply(sentences, 
                 function(sentence, pos.words, neg.words)
                 {  sentence = gsub("[[:punct:]]", "", sentence)
                 sentence = gsub("[[:cntrl:]]", "", sentence)
                 sentence = gsub('\\d+', '', sentence)
                 tryTolower = function(x)
                 {         y = NA
                 try_error = tryCatch(tolower(x), error=function(e) e)
                 if (!inherits(try_error, "error"))
                   y = tolower(x)
                 return(y)
                 }
                 sentence = sapply(sentence, tryTolower)
                 word.list = str_split(sentence, "\\s+")
                 words = unlist(word.list)
                 pos.matches = match(words, pos.words)
                 neg.matches = match(words, neg.words)
                 pos.matches = !is.na(pos.matches)
                 neg.matches = !is.na(neg.matches)
                 score = sum(pos.matches) - sum(neg.matches)
                 return(score)
                 }, pos.words, neg.words)
  scores.df = data.frame(text=sentences, score=scores)
  return(scores.df)
}


#트위터용_감성분석함수
score.sentiment = function(sentences, pos.words, neg.words)
{
  scores = laply(sentences, 
                 function(sentence, pos.words, neg.words)
                 {
                   tryTolower = function(x)
                   {
                     y = NA
                     try_error = tryCatch(tolower(x), error=function(e) e)
                     if (!inherits(try_error, "error"))
                       y = tolower(x)
                     return(y)
                   }
                   sentence = sapply(sentence, tryTolower)
                   word.list = str_split(sentence, "\\s+")
                   words = unlist(word.list)
                   pos.matches = match(words, pos.words)
                   neg.matches = match(words, neg.words)
                   pos.matches = !is.na(pos.matches)
                   neg.matches = !is.na(neg.matches)
                   score = sum(pos.matches) - sum(neg.matches)
                   return(score)
                 }, pos.words, neg.words)
  scores.df = data.frame(text=sentences, score=scores)
  return(scores.df)
}

# 부정 긍정 단어 가지고 오기
pos.words = scan('positive-words.txt', what='character', comment.char=';')
neg.words = scan('negative-words.txt', what='character', comment.char=';')


#MLB 야구팀 2개 트위터 가져오기
yankees.tweets <- searchTwitter('#yankees', , n=500, lang="en")
redsox.tweets <- searchTwitter('#redsox', , n=500, lang="en")
rays.tweets <- searchTwitter('#rays',  n=500, lang="en")

# 트위터에서 텍스트만 가져오기
yankees.text = sapply(yankees.tweets, function(t) t$getText())
redsox.text = sapply(redsox.tweets, function(t) t$getText())
rays.text = sapply(rays.tweets, function(t) t$getText())

#특정문자 지우기
yankees.text <- gsub('\\d+', '', yankees.text)
yankees.text <- gsub("[:punct:]","",yankees.text)
yankees.text <- gsub("[[:cntrl:]]", "", yankees.text)
yankees.text

redsox.text <- gsub('\\d+', '', redsox.text)
redsox.text <- gsub("[:punct:]","",redsox.text)
redsox.text <- gsub("[[:cntrl:]]", "", redsox.text)
redsox.text

rays.text <- gsub('\\d+', '', rays.text)
rays.text <- gsub("[:punct:]","",rays.text)
rays.text <- gsub("[[:cntrl:]]", "", rays.text)
rays.text


#감성 분석
yankees.scores <- score.sentiment(yankees.text, pos.words, neg.words)
redsox.scores <- score.sentiment(redsox.text, pos.words, neg.words)
rays.scores <- score.sentiment(rays.text, pos.words, neg.words)

#결과 확인
class(yankees.scores)
str(yankees.scores)
table(yankees.scores$score)
table(redsox.scores$score)
table(rays.scores$score)


#그래프 그리기 위해서 열 추가
yankees.scores$team = 'Yankees'
redsox.scores$team = 'Red Sox'
rays.scores$team = 'Rays'

#데이터 프레임 합치기
aleast.scores = rbind(yankees.scores,  redsox.scores, rays.scores)

#데이터 시각화

ggplot(data=aleast.scores, aes(x=score, group=team)) +
  geom_bar(aes(fill=team), binwidth=1) + 
  facet_grid(team~.) +
  theme_bw() +
  labs(title="Barplot - MLB Sentiment Scores")

ggplot(data=aleast.scores, aes(x=team, y=score, group=team)) +
  geom_boxplot(aes(fill=team)) +
  geom_jitter() +
  labs(title="Boxplot - MLB Sentiment Scores")