• R-7 2020.09.05
반응형

#구글 스프레드시트 ->개인에서 누러기->내용추가->파일->업로드->
잴위에 x라는 열이름이 생긴다.

open map
install.packages("ggmap")
library(ggmap)
library(ggplot2)
library(dplyr)
library(rvest)#read_html

html.airports <- read_html("https://en.wikipedia.org/wiki/List_of_busiest_airports_by_passenger_traffic")
html.airports
df <- html_table(html_nodes(html.airports, "table")[[1]],fill= T) #[[]]list중에서 첫번째것 
#html_table 표 가지로 가는 것 
#html_nodes 노드 가지로 가는 것 

head(df)
head(df$Airport)
colnames(df)
colnames(df)[6] <- "total" #있으면 보여주고 없으면 만들어준다.
df$total
df$total <- gsub(',','',df$total)#정규표현식 할떄 나오는 것 g는 global하는 것 
#전부다 대체 하는 것이다. ,를 찾아서 ''으로 대체 한다.
df$total <- as.numeric(df$total)#character->숫자로 바꾸는 것 
df$total
#df$total <- as.double(df$total,5)
#df$total
typeof(df$total)

df <- head(df,10)
df
write.csv(df$Airport,file="geoname.csv")#공항이름으로 구글에 들어가는 방법을 진행하고 있습니다.
#geoname.csv읽어오면 캐리터는 글자로 일지 않고 글자는 범주로 읽어온다.

숫자를 글자로 인식하고 ->범주로 인식한다.
string ->factor로 받아들인다.
그래서 factor->as.character->numeric으로 바꾼다.

#구글 스프레드시트 ->개인에서 누러기->내용추가
geo <- read.csv("geoname - geoname.csv",stringsAsFactors = F)#문자를 factor로 하는 것이 아니라 chr로 읽어 온다.
geo
geo <- na.omit(geo) 
str(geo)

#아래 방법을 사용하는게 좋다.
library(readr)
geo <- read_csv("geoname - geoname.csv")
str(geo)

getwd()

#구글 스프레드시트 ->개인에서 누러기->내용추가
geo <- read.csv("geoname - geoname.csv")
geo
geo <- na.omit(geo) # geo <- geo[-1,]
geo

df <- cbind(df, lat = geo$Latitude, lot = geo$Longitude)
install.packages("maps")
library(maps)
world <- map_data("world")
world
#install.packages("reprex")
#library(reprex)

str(df)
dplyr::glimpse(df)
str(df)
#소수점 빼기 -1
df$lot <- as.numeric(as.character(df$lot))# Factor범주형이기때문에 
df$lat <- as.numeric(as.character(df$lat))
#소수점 빼기 -2 #안됨 숫자만 가능함 
#round(df$lat, digits = 5) 
df

as.numeric(df$lot)#1,2,3,4,5 이런식으로 나온다.
df$lot
as.double(df$lot,-5)
head(world,6)
head(df)
format(round(df$lot, 5), nsmall = 5)
str(world)

ggplot(df, aes(x = lot, y = lat))+
  geom_polygon(data = world, aes(x = long, y =lat, group = group ), fill="grey75", color="grey70")+
  geom_point(data = df, color = rainbow(10), alpha = .25, aes(size= total))+
  geom_point(data = df, color = rainbow(10), alpha = .75, shape = 1, aes(size = total))+
  geom_segment(data = df, aes(x =lot, y = lat,xend = lot, yend = lat, colour = Airport ))

 

numeric->하면 아래 너무 많이 짜른다.

#twitter
----------------------------twitee----------
load("Obama.rda")
load("Trump.rda")

save(tweets_Obama,file="Obama.rda")
save(tweets_Trump,file="Trump.rda")
tweets_Obama
tweets_Trump
View(tweets_Trump)
library(twitteR)

#tweets_Trump <- searchTwitter("Obama",lang="en",n =1000)
tweets_Obama <- twListToDF(tweets_Obama)#dataframe으로 바꿔주는 
Obama_text <- tweets_Obama$text#트위트 내용만 가져오기
Obama_text
head(Obama_text)
names(tweets_Obama)

tweets_Obama$text#이 열만 가져와서 하기 

Obama_text <- gsub("\\W"," ",Obama_text)#빈칸으로 바꿨습니다.W대문자 특수문자 바꾸는 것 
Obama_df <- as.data.frame(Obama_text)#다루기 편한 ggplot할때 는 dataframe의 형태로 바꿨다.
length(Obama_df)
length(Obama_text)

#Trump
#tweets_Trump <- searchTwitter("Trump,lang="en",n =1000)
tweets_Trump <- twListToDF(tweets_Trump)
Trump_text <- tweets_Trump$text
head(Trump_text)
names(tweets_Trump)

tweets_Trump$text

Trump_text <- gsum("\\W"," ", Trump_text)
Trump_df <- as.data.frame(Trump_text)

#단위를 뽑아서 사전을 만들었다.
#긍정적이면 3점 아니면 2점 
#hu.liu.pos = readLines('https://www.dropbox.com/sh/3xctszdxx4n00xq/AAA_Go_Y3kJxQACFaVBem__ea/positive-words.txt?dl=1');
#hu.liu.neg = readLines('https://www.dropbox.com/sh/3xctszdxx4n00xq/AABTGWHitlRZcddq1pPXOSqca/negative-words.txt?dl=1');


#1. url에서 가져오는 것 
hu.liu.pos = readLines('https://www.dropbox.com/sh/3xctszdxx4n00xq/AAA_Go_Y3kJxQACFaVBem__ea/positive-words.txt?dl=1');
hu.liu.neg = readLines('https://www.dropbox.com/sh/3xctszdxx4n00xq/AABTGWHitlRZcddq1pPXOSqca/negative-words.txt?dl=1');

sample=c("You're awesome and I love you","I hate and hate and hate. So angry. Die!","Impressed and amazed: you are peerless in your achievement of unparalleled mediocrity.")
result=score.sentiment(sample,hu.liu.pos,hu.liu.neg)
result

#2. 파일로 가져오는 것 
pos.word <- scan("positive-words.txt",what ="character",comment.char = ";")#scan으로 이파일을 읽는다.
neg.word <- scan("negative-words.txt",what ="character",comment.char = ";")
pos.word
neg.word

score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
  require(plyr);
  require(stringr);
  scores = laply(sentences, function(sentence, pos.words, neg.words) {
    sentence = gsub('[^A-z ]','', sentence)
    sentence = tolower(sentence);
    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, .progress=.progress );
  scores.df = data.frame(score=scores, text=sentences);
  return(scores.df);
}

Obama_scores <- score.sentiment(Obama_text, pos.word, neg.word, .progress = "text")
str(Obama_scores)
Obama_scores$score
hist(Obama_scores$score)

Trump_scores <- score.sentiment(Trump_text,pos.word, neg.word, .progress = "text")
Trump_scores$score
hist(Trump_scores$score)

#margin설정
#par(mar=c(2,4,2,2))#여백주는 함수

a <- dim(Obama_scores)[1]
b <- dim(Trump_scores)[1]

alls <- rbind(as.data.frame(cbind(type= rep("Obama",a), score = Obama_scores[,1])),
             as.data.frame(cbind(type= rep("Trupm",a), score = Trump_scores[,1])))
str(alls)
alls$score <- strtoi(alls$score)

library(ggplot2)
ggplot(alls, aes(x = score, color = type))+geom_density(size = 1)


nrow(Obama_scores)
nrow(Trump_scores)

#rbind #row로 묶어주는것 type열과 score이라는 열을 묶어준다.
#Obama 를 a= 1000번 복제하세요  score이라는 열을 잡아서 Obama_scores첫번째 열을 꺼내서 하는 것 
#str(Obama_scores)
#text가 범주형 
library(dplyr)
Obama_scores[,1]
str(alls)
distinct(alls$type)
str(as.character(alls$type))
n_distinct(as.character(alls$type))
distinct(as.character(alls$type))#오류 난다. 클래스 "character"의 객체에 적용된 'distinct_'에 사용할수 있는 메소드가 없습니다

4. 동적 시각화 
“plotly”는  Interactive 그래프를 그려주는 패키지 ggplot2로 완성된 그래프를 단순히 ggplotly( ) 에  넣으면 된다. 
https://plot.ly/r/

rCharts 는  자바스크립트 기반인 D3, Highcharts 를  R에서 그려주는 패키지. 
require(devtools) ; install_github('rCharts', 'ramnathv') 
googleVis google 에서 만든 Interactive 그래프를 그려주는 라이브러리 
https://plot.ly/->dash->dash

https://plot.ly/r/

 

Plotly R Graphing Library

Plotly's R graphing library makes interactive, publication-quality graphs. Examples of how to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, and 3D (WebGL based) charts.

plotly.com

#-------------------------plotly-----------------

mpg
ggplot(data = mpg, aes(x = displ , y = cty, color = drv))+
  geom_point()+xlim(3,5)+ylim(10,25)#2차원 산점도
   
ggplot(data = mpg, aes(x = displ , y = cty, color = drv))+
  geom_point()

install.packages("plotly")
library(plotly)
p1 <- ggplot(data = mpg, aes(x = displ , y = cty, color = drv))+
  geom_point()
ggplotly(p1)

p2 <- ggplot(mpg, aes(x= class, fill= drv))+geom_bar()
ggplotly(p2)

p2 <- ggplot(mpg, aes(x= class, fill= drv))+geom_bar(position="dodge")#bar를 옆으로 펼쳐지는 것 position="dodge"
ggplotly(p2)

#google
#rCharts
install.packages("devtools")
library(devtools)

library(ggplot2)
install_github('ramnathv/rCharts')
install_github('saurfang/rCharts',ref= 'utf8-writelines')
library(rCharts)
hair_eye_male <- subset(as.data.frame(HairEyeColor),Sex =="Male")
nPlot(Freq ~ Hair , group ="Eye" ,data = hair_eye_male, type ="multiBarChart")
rPlot(mpg ~ wt | am + vs, data = mtcars, type ="point", color ="gear")#4개로 쪼개서 보기 좋게 보여준다.


mp3 <- Leaflet$new()
map3$setView(c(51.505, -0.09), zoom = 13)
map3$marker(c(51.5, -0.09),bindPopup ="<p> I am a popup </p>")#영국 
map3$marker(c(51.495, -0.083),bindPopup="<p> Hi~ </p>")
library(dplyr)
mp3 <- Leaflet$new()
mp3
map3$setView(c(37.532600, 127.024612), zoom = 13)
map3$marker(c(37.5, 127.0),bindPopup ="<p> I am a popup </p>")#영국 
map3$marker(c(51.495, -0.083),bindPopup="<p> Hi~ </p>")

m1 <- mPlot(x ="date" , y =c("psavert","uempmed"), type ="Line", data =economics)
m1$set(pointSize = 0, linewidth = 1)
m1


map3 <- Leaflet$new() 
map3$setView(c(51.505, -0.09), zoom = 13) 
map3$marker(c(51.5, -0.09), bindPopup = "<p> I am a popup </p>") 
map3$marker(c(51.495, -0.083), bindPopup = "<p> Hi~ </p>") 
map3
https://www.youtube.com/results?search_query=cs231n
https://www.youtube.com/results?search_query=cs230
https://www.youtube.com/results?search_query=3blue1brown

Google Map Api 활용한 지도 시각화
ggmap패키지2.7 버전설치하고인증키등록하기 
get_map() 함수 
◉ location 
- 불러올 지역의 중심을 ‘지역명’, ‘주소’, 또는 c(lon = 경도, lat = 위도) 처럼 위경도 좌표로 지정 
- Windows 사용자들은 ‘지역명’이나 ‘주소’를 한글로 지정하려면 반드시 enc2utf8() 함수를 이용하여 한글의 인코딩 방식을 UTF-8으로 변경 
◉ zoom 
- 2 ~ 21 사이의 정수를 입력. 숫자가 커질수록 확대된 지도가 출력. 예를 들어 3은 대륙(Continent), 10은 도시(City), 21은 건물 (Building) 크기
get_map() 함수 
◉ maptype 
- ‘terrain’, ‘terrain-background’, ‘satellite’, ‘roadmap’, ‘hybrid’, ‘toner’, ‘watercolor’ 중에서 하나를 지정 
◉ source 
- ‘google’, ‘osm’, ‘stamen’, ‘cloudmade’ 중 하나를 선택
get_map
myLocation->위성으로 
#leaflet은 인터랙티브한 지도를 구현할 수 있게 해주는 오픈소스 자바스크립트 라이브러리이다 
#R의 leaflet 패키지는 R에서 데이터를 가지고 쉽게 Leaflet 지도를 생성할 수 있게 해준 다 

 

install.packages("leaflet")
library(leaflet)
library(dplyr)
library(readxl)
library(stringx)

#http://www.weather.go.kr 접속한다.

1. [지진ㆍ화산] → 2. [국내지진 목록]
1. 날짜 지정(2009.01.01~2019.12.03) → 2. [검색하기] → 3. [엑셀 다운로드]
#다운받은 파일을 엑셀을 실행시켜 sheet가 몇 개인지 확인한다 
#워킹디렉토리에 넣은 후 불러오기한다 

eq <- read_xlsx('국내지진.xlsx')
View(eq)
# 북한을 제외한다
eq01 <- eq[grep("북한",eq$위치,invert = T),]
#eq01 <- eq[grep("북한",eq$위치,invert = F),]
#정규표현식 grep ("단어", 위치 , )
#invert = T북한행을 빼고 보여주는 것 
#invert = F북한행만 보여주는 것 
eq[grep("북한",eq$위치,invert = T),]
eq[grep("북한",eq$위치,invert = F),]
View(eq01)
# 위도, 경도 뒤의 불필요한 문자를 삭제한 후 숫자형으로 바꾸어 준다 
eq01$위도 <- str_replace(eq01$위도 , ' N','')#불필요한 부분 빼야 한다. 공백하고 N을 아무것도 없이 바꾼다.
eq01$위도 <- as.numeric(eq01$위도)#character을 numeric으로 바꾼다.
eq01$경도 <- str_replace(eq01$경도,' E','')
eq01$경도 <- as.numeric(eq01$경도)

str(eq01)

leaflet() %>% addTiles() %>% addMarkers(lng=eq01$경도, lat=eq01$위도, popup=paste0("발생시각 : ", eq01$발생시각, "<br/>위치: ", eq01$위치, "<br/>규모 : ", eq01$규모))

Kormaps2014 package
devtools::install_github("cardiomoon/kormaps2014") 
devtools::install_github("cardiomoon/moonBook2")
library(kormaps2014) 
library(moonBook2)

# http://www.localdata.kr 접속한다
# 1. 식품 → 2. 음식점 아이콘 아래의 [바로가기]
# 창 아래쪽으로 이동하여 [EXCEL] 클릭하여 파일을 다운로드한다

Tips
# 다운받은 파일을 열어보고 자료의 속성과 구조를 파악한다 
# 운영체제나 프로그램에 따라 한글인코딩 방식이 달라지므로 항상 유의한다(csv, txt 파일) 
# 객체를 생성할 때 가급적 간단하게 식별가능하게 정의 한다 
# 기존의 성공한 데이터를 이용하여 가공하도록 한다 
# 항상 데이터의 속성과 구조에 유의하여 가공을 하도록 한다 
# 데이터 가공할 때에 효율적으로 사용해야 한다(시간과 노력의 비용 염두) 
# 다양한 관점과 시각으로 접근하여 효율성을 높인다 
# 필요한 패키지가 설치되고 로드되어 있는지 확인한다 
엑셀은 sheet확인하기
2008년도 관악구 정보 확인해야 한다.

https://rpubs.com/cardiomoon/222145

 

devtools::install_github("cardiomoon/kormaps2014") 
devtools::install_github("cardiomoon/moonBook2")
library(kormaps2014) 
library(moonBook2)
areacode
korpop2 <- kormaps2014::korpop2
kormap1 <- kormaps2014::kormap1

korpop2
str(kormap1)#시 도 
str(kormap2)#구단위
str(kormap3)#동단위
str(korpop1)#invalid multibyte string, element 3
str(korpop2)#invalid multibyte string, element 3
str(korpop3)#invalid multibyte string, element 3
korpop2 <- changeCode(korpop2)#
korpop1 <- changeCode(korpop1)

library(ggplot2)
install.packages("mapproj")
library(mapproj)
library(dplyr)
theme_set(theme_gray(base_family = "NanumGothic"))
#https://wikidocs.net/41145
#2015년 인구총조사 중 “총인구_명”으로 단계구분도를 그리려면 다음과 같이 합니다.
kormap1
kormap1$lat
kormap1$long
str(kormap1)
ggplot(korpop1,aes(map_id= code, fill =총인구_명))+
  geom_map(map = kormap1, colour="black",size=0.1)+
  expand_limits(x= kormap1$long,y = kormap1$lat)+
  scale_fill_gradientn(colours = c('white','orange','red'))+
  ggtitle('2015년도 시도별 인구분포도')+coord_map()

#moonBook2패키지에 있는 ggChoropleth()함수를 이용하면
#훨씬 간편하게 단계구분도를 그릴 수 있습니다.
#다음은 시군구별, 읍면동별 단계구분도의 예제입니다.
#korpop2->kormap2로 하면서 남자_명으로 한다.
ggChoropleth(korpop2,kormap2,fillvar = "남자_명")

kormap3 <- kormaps2014::kormap3
korpop3 <- kormaps2014::korpop3
str(kormap3)
str(korpop3)
korpop3 <- changeCode(korpop3)
ggChoropleth(korpop3,kormap3,fillvar="주택_계_호")

area2code
str(korpop3)
str(kormap3)

areacode <- changeCode(areacode)
str(areacode)
ggChoropleth(korpop3,kormap3,fillvar="총인구_명",subarea=c("전라","광주"))

rm(list = ls())

remove.packages(c("ggiraphExtra", "tibble", "ggplot2"))
install.packages(c("ggiraphExtra", "tibble", "ggplot2"))
install.packages("devtools")
remove.packages(c("moonBook2"))
remove.packages(c("kormaps2014"))
library(kormaps2014) 
library(moonBook2)

ggChoropleth(korpop2,kormap2,fillvar="남자_명",interactive=TRUE)
ggChoropleth(korpop3, kormap3, fillvar = "남자_명",interactive= T,subarea=c("전라","광주"),tooltip="행정구역별_읍면동")

summary(tbc)
tbc1= tbc[tbc$year %in% c(2001,2005,2010,2015),]
ggChoropleth(tbc1,kormap1,fillvar="NewPts",facetvar="year",tooltip="name",interactive=T)

areacode

# 1. 식품 → 2. 음식점 아이콘 아래의 [바로가기]
# 창 아래쪽으로 이동하여 [EXCEL] 클릭하여 파일을 다운로드한다
install.packages('rlang') library(rlang) library(readxl) library(dplyr)
# 서울특별시 일반음식점 엑셀파일을 불러오기한다. 
seoulres<- read_excel("6110000_서울특별시_07_24_04_P_일반음식점.xlsx") View(seoulres)

# 엑셀프로그램으로 해당 파일을 열어 시트가 여러개인지 확인해야 한다
# 시트가 여러개일때 따로 따로 불러서 데이터를 합쳐야 한다 # 다시 시트별로 각각 불러 모은다 
seoulres01<- read_excel("6110000_서울특별시_07_24_04_P_일반음식점.xlsx", sheet = '일반음식점_1') 
seoulres02<- read_excel("6110000_서울특별시_07_24_04_P_일반음식점.xlsx", sheet = '일반음식점_2’)
# 두개의 데이터를 병합한다 seoulres03 <- rbind(seoulres01, seoulres02)
View(seoulres03)

str(seoulres03)

# 필요한 부분을 축출한다 
seoulch <- seoulres03 %>% filter(상세영업상태명 == '영업' & 위생업태명 %in% c('호프/통닭','통닭(치킨)'))
View(seoulch)

#열을 뽑는다.
# 어떤 변수를 활용할 것인가? 결측치가 적은 것을 택하자 
sum(is.na(seoulch$소재지우편번호))
sum(is.na(seoulch$소재지전체주소))

#1. 소재지전체주소 변수를 선택할 경우 해당변수의 결측치 제거 
seoulch01 <- na.omit(seoulch$소재지전체주소)
View(seoulch01)

# 문자열 함수 패키지를 로드한다. 
library(stringr)

# 정규식을 사용해서 '소재지전체주소'에서 '구명'만 추출한다. 
seoulch02 <- substr(seoulch01, 7, 10)#서울특별시 구로구 
#7->10자리 까지 뽑는다.
# 공백제거seoulch03 <- gsub(" ", "", seoulch02) 
seoulch02
seoulch03 <- gsub(" ","",seoulch02)#공백을 없앤다.
View(seoulch03)
unique(seoulch03)

# 필요없는 문자 제거 
seoulch04 <- str_replace_all( seoulch03, "[을충신필명중오인남다수북흥회쌍입광정저순만황초서장태주무산]","")
View(seoulch04)
str(seoulch03)
names(seoulch03)

#중구행만을 따로 떼고 가공한 후 다시 새로 붙여보자 
# 중구행만을 축출하자
seoulchch <- seoulch03[276:616]
View(seoulchch)
unique(seoulchch)

# 중구 뒤에 나오는 글자를 삭제하자 
seoulchch01 <- substr(seoulchch, 1,2)
View(seoulchch01)
unique(seoulchch01)

# 중구행을 삭제하여 새로 가공된 중구행을 결합할 준비를 하자
seoulch05 <- seoulch03[-(276:616)]
View(seoulch05)
unique(seoulch05)

# 가공된 중구행을 붙인다 
seoulch06 <- c(seoulchch01,seoulch05)
View(seoulch06)
unique(seoulch06)

# 구별로 빈도수를 구한다 
seoulch06 <- table(seoulch06)
View(seoulch06)
seoulch06
nrow(seoulch06)

# 2. 소재지우편번호(구우편번호)를 이용하는 방법 
seoulch07 <- na.omit(seoulch$소재지우편번호) 
View(seoulch07)

# 우편번호 앞 세자리를 추출한다 ->구로 구분한다.
seoulch08 <- substr(seoulch07, 1,3) 
View(seoulch08)

# 구별로 합산한다 
seoulch09 <- table(seoulch08)
View(seoulch09)
unique(seoulch08)

# 구명 객체를 생성하여 데이터를 만들 준비를 하자 
# 공통 키로 해서 
gu<- c("중구", "종로구", "서대문구", "마포구", "은평구", "동대문구", "중랑구", "도봉구","성동구", "강동구", "강남구", "성북구", "서초구", "송파구", "노원구", "용산구", "강북구", "광진구", "영등포구", "관악구", "구로구", "금천구", "동작구", "강서구", "양천구")

# 구명 객체와 병합한다 
seoulch10 <- data.frame(gu, seoulch09) 
View(seoulch10)

# 트리맵 시각화 
install.packages("treemap")
library(treemap)
treemap(seoulch10, index = "gu", vSize ="Freq", title = "서울시 구별 치킨집수")
#많은 것 부터 

# 패키지에 내장되어있는 기존의 데이터를 가공한다 
ch <- korpop2[1:25,] #1행부터 25까지 행을 보여준다.
ch 

# 필요한 변수를 추출한다 
ch01 <- select(ch, c("행정구역별_읍면동",'code'))
str(ch01)

# 한글 인코딩을 바꾸어준다 
ch01
ch02 <- changeCode(ch01)
View(ch02)
ch02

#각각의 변수의 속성을 문자로 바꾸어 주어 데이터 병합을 준비하자
ch02$행정구역별_읍면동
ch02$행정구역별_읍면동 <- as.character(ch02$행정구역별_읍면동) 
ch02$code <- as.character(ch02$code)

# 데이터 병합을 위해 정렬시킨다 
ch03 <- arrange(ch02, ch02$행정구역별_읍면동)

## gu 변수명을 '행정구역별_읍면동'으로 바꾸어준다
seoulch10
seoulch11 <- rename(seoulch10, '행정구역별_읍면동'='gu','치킨집수'=Freq)
View(seoulch11)
str(seoulch11)

# 마찬가지로 속성을 바꾸어 주어 병합을 준비한다 
#character속성으로 바꾸어준다.
seoulch11$행정구역별_읍면동 <- as.character(seoulch11$행정구역별_읍면동)
# 필요없는 부분을 삭제한다 
seoulch12 <- select(seoulch11, -seoulch08)
str(seoulch12)

# 정렬한다 
#정렬하여 오차없이 매칭해준다.
seoulch13 <- arrange(seoulch12, seoulch12$행정구역별_읍면동)
View(seoulch13)

# 데이터를 병합한다 
#korpop2 ->ch03 정렬되여 있는 것을 seoulch13정렬되여 있는 것과 합친다.
seoulch14 <- cbind(ch03,seoulch13)
seoulch14

# 정렬한다 
# 합친 seoulch14것을 마지막 하나를 뺀다.
seoulch15 <- seoulch14[,-1]
View(seoulch15)

# 시각화 
ggChoropleth(seoulch15,kormap2,fillvar="치킨집수",interactive=TRUE,subarea='서울',tooltip="행정구역별_읍면동",title='서울시 구별 치킨집수'  )

 

 

반응형

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

R-9  (0) 2020.09.05
R-8  (0) 2020.09.05
R-6  (0) 2020.09.05
R-5  (0) 2020.09.05
R-4  (0) 2020.09.05

+ Recent posts