Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

류동균의 R 공부방입니다.

프리미어리그 데이터분석(feat 크롤링) 본문

Data Analysis

프리미어리그 데이터분석(feat 크롤링)

R쟁이 2019. 8. 6. 22:07

2번째글에서는 크롤링을 통해 필요한 데이터를 추출하고 그것을 가공하는것을 배워보았다. 

크롤링을 하기위해서는 우선 DV, rvest라는 패키지를 인스톨 해야한다. 그리고 url주소를 얻어야한다. 이때 url 주소가 가지는 일정한 패턴을 파악하는것이 중요하다.

다음의 url에서는 category, year, tab 이라는 변수를 가지기때문에 이러한 변수들의 값을 잘 바꿔 원하는 데이터를 추출할 수 있다. 다음과같이 year라는 변수의 값을 for문으로 바꿔가며 epl카테고리의 year(연도)별 player 축구선수들의 목록을 가져 올 수 있다.

 

# url 주소 추출

# url <- "https://sports.news.naver.com/wfootball/record/index.nhn?category=epl&year=2010&tab=player"

 

# for문으로 연도별로 가져오기 위해 years 라는 변수를 사용

years <- 2010

url <- paste0("https://sports.news.naver.com/wfootball/record/index.nhn?category=epl&year=",years,"&tab=player")


#url주소의 html화
url_html <- url %>% read_html()

 

# 기본형은html_nodes(x,css) ,html_nodes(x,xpath) 인데

 css경로를 넣어주면 직관적이지만 중복된 css가 딸려나올수있기때문에 xpath를 쓴다 xpath는 사람의 주민번호와같은 고유의 번호를 가지고 있기때문에 xpath를 사용하면 원하는 자료만 가져올 수 있다.  


url_raw <- html_nodes(url_html, xpath = '//*[@id="wfootballPlayerRecordBody"]/table')
epl_table <- url_raw %>% html_table() %>%  as.data.frame()
str(epl_table)

다음과같이  2010 epl 득점순위 테이블을 가져올 수 있다. 하지만 데이터의 선수 컬럼의 형식이 마음에 들지 않기 때문에 변형을 해야한다.

# strsplit을 사용해 epl_table의 2번쨰 컬럼을 "\n                "를 기준으로 분리해서 데이터 프레임화 시킨다. t()로 행열을 전치시킴
team_player <- strsplit(epl_table[,2],"\n                ") %>% 
  as.data.frame() %>% 
  t() %>% 
  as.data.frame()
#rowname 제거
rownames(team_player) <- NULL


#  team_player의 컬럼들을 character로 바꿈
for(i in 1:ncol(team_player)) { 
team_player[,i] <- team_player[,i] %>% 
  as.character()
}

 

#team_player의 테이블과 total_epl_table을 조합하여 원하는 형태로 data.frame을 만듬
epl_table[,2] <- team_player[,1]

total_epl_table <- cbind(epl_table[,1:2], "소속팀"=team_player[,2],epl_table[,3:ncol(epl_table)])

 

#mutate()를 사용하면 몇년도인지를 나타내는 컬럼 생성 mutate()는 열을 추가할때 사용하는 함수로 dplyr패키지에 있다.
total_epl_table <- total_epl_table %>%
  mutate(years = years)
# 각연도별로 데이터를 가져온것을 하나의 데이터프레임으로 rbind
total_epl_player_table <- rbind(total_epl_player_table, total_epl_table) 

 

#크롤링을 할때 봇으로 인식되지 않기 위해서 10초동안 시스템을 멈춤
Sys.sleep(10)
}

#위의 함수들을 for( years in 20xx : 20xx) {} 와 같이 for문에 넣어 years를 변수로 사용하여 연도별 득점순위를 테이블을 통합할 수 있음

total_epl_player_table


#가급적 한글을 사용하지 않는것이 좋기때문에 컬럼이름을 영어로 바꿔주도록하는게 좋음 
colnames(total_epl_player_table) <- c("ranking","player","team","goal",
                                      "assist","attack_point","shooting",
                                      "foul","alert","off","corner_kick",
                                      "penalty_kick","offside","effective_shot",
                                      "match","years")

 

#완성된 자료를 토대로 데이터를 조작하기위해서는 dplyr패키지가 아주 유용하다 group_by(), summarise(), arrange(), 

select(), filter() 등 여러가지 함수들이 들어있다.

#arrange() 정렬을 하는 기능 sort()와 유사하다

#group_by(), summarise() 는 함께 사용되고 그룹별로 최대값이나 평균을 구할 때 자주 사용된다.


#선수별 골 총합
total_epl_player_table %>% 
  group_by(player) %>% 
  summarise(goal = sum(goal)) %>% 
  arrange(desc(goal)) %>% 
  as.data.frame()
#선수별 평균골
total_epl_player_table %>% 
  group_by(player) %>% 
  summarise(goal = mean(goal)) %>% 
  arrange(desc(goal)) %>% 
  as.data.frame()
#팀의  골 총합
total_epl_player_table %>% 
  group_by(team) %>% 
  summarise(goal = sum(goal)) %>% 
  arrange(desc(goal)) %>% 
  as.data.frame()
#팀의 골 평균
total_epl_player_table %>% 
  group_by(team) %>% 
  summarise(goal = mean(goal)) %>% 
  arrange(desc(goal)) %>% 
  as.data.frame()

total_epl_player_table %>% 
  group_by(team,player) %>% 
  summarise(goal = sum(goal)) %>% 
  arrange(desc(goal)) %>% 
  as.data.frame()

total_epl_player_table %>% 
  group_by(player,team) %>% 
  summarise(goal = sum(goal)) %>% 
  arrange(desc(goal)) %>% 
  as.data.frame()


# group_by player
total_epl_player_table %>% 
  group_by(player) %>%  
  summarize(goal = sum(goal)) %>%
  arrange(desc(goal)) %>%
  as.data.frame()

# group_by team
total_epl_player_table %>% 
  group_by(team) %>%  
  summarize(goal = sum(goal)) %>%
  arrange(desc(goal)) %>%
  as.data.frame()

# group_by team
total_epl_player_table %>% 
  group_by(team,player) %>%  
  summarize(goal = sum(goal)) %>%
  arrange(desc(goal)) %>%
  as.data.frame()



# DT Packages
https://rstudio.github.io/DT/
datatable(total_epl_player_table)