해들리 위캄이 데이터 처리의 효율성을 위해서 만든 패키지를 합쳐 타이디벌스라고 지칭합니다.

이에 포함되는 대표적인 패키지는 저번에 포스팅한 dplyr이며 여기에 추가적으로 tidyr도 자주 쓰인다고 합니다.

따라서 이 두가지 패키지를 활용한 데이터 전처리 방법엔 무엇이 있는지 정리해봤습니다.

1. bind_cols(=cbind)와 bind_rows(=rbind)

  • 데이터를 열방향으로 병합할때 쓰는 cbind와 행방향으로 병합할때 쓰는 rbind의 역할을 하는 dplyr 함수가 있습니다.
  • bind_rows와 bind_cols를 활용합니다.
  • 이들 함수는 data frame 과 tibble에만 적용 가능합니다.
    sportLeague <- tibble(sport = c("Hotkey", "Baseball", "Football"),
                        league = c("NHL", "MLB", "NFL"))
    trophy <- tibble(trophy = c("Stanley Cup", "Commissioner's Trophy",
                              "Vince Lombardi Trophy"))
    trophies1 <- bind_cols(sportLeague, trophy)
    

2. dplyr를 사용한 조인

  • 왼쪽 외부 조인은 왼쪽 테이블의 모든 행은 유지되고 오른쪽 테이블에서는 매칭되는 행들만 포함된다
    left_join(diamonds, diamondColor, by=c('color'='Color'))
    
  • 오른쪽 외부 조인은 오른쪽 테이블의 모든 행은 유지되고 왼쪽 테이블에서는 매칭되는 행들만 포함된다
    right_join(diamonds, diamondColor, by=c('color'='Color'))
    
  • 내부조인(inner join)은 양쪽 테이블에서 모두 매칭되는 행들만 반환한다.
    inner_join(diamonds, diamondColor, by=c('color'='Color'))
    
  • 완전 외부 조인(full outer join)은 두 테이블에 있는 모든 행들을 반환한다.
    full_join(diamonds, diamondColor, by=c('color'='Color'))
    
  • 세미 조인(semi join)은 두 테이블을 합치는 것은 아니고 오른쪽 테이블과 매칭되는 행에 왼쪽 테이블의 행의 첫 행들을 반환한다. (Vlookup)
    semi_join(diamondColor, diamonds, by=c('Color'='color'))
    
  • 안티 조인(anti join)은 세미 조인의 반대 개념이다.
    anti_join(diamondColor, diamonds, by=c('Color'='color'))
    
  • 세미 조인이나 안티 조인은 filter, unique 함수를 사용해 같은 값을 얻을 수 있다.
    diamondColor %>% filter(Color %in% unique(diamonds$color))
    

    3. 데이터 포맷 변환 (tidyr의 gather, spread 함수)

  • 기존에는 melt와 dcast 함수를 사용해 데이터를 변환```
  • tidyr 패키지는 reshape2 패키지의 차기버전 (계산 속도와 사용 편의성 증대)

  • gather 함수는 기존의 melt 함수와 같은 역할을 한다.
    emotion %>%
    gather(key=Type, value=Measurement, Age, BMI, React, Regulate)
    
  • spread 함수는 기존의 dcast 함수와 같은 역할을 한다.
    emotionLong %>%
    spread(key=Type, value=Measurement)
    

  • 출처 : 데이터 과학 입문자를 위한 R