R에는 수많은 데이터 핸들링 패키지들이 존재한다. 오늘은 그중에서도 dplyr, tidyr, data.table 패키지에 대해 간략히 정리하고자 한다. 우선 R의 기본함수를 먼저 알아보자.
🌈기본함수
핸들링에 유용하다고 생각되는 R의 기본함수로는 apply와 sapply, aggregate가 있다. apply는 array나 matrix에 대해 행, 열 또는 그 이상의 차원별로 함수 적용결과를 반환하는 함수이다. sapply함수는 list별로 함수를 적용하고 다시 list로 반환하는 ldapply함수를 data.frame의 형태로 반환할 수 있도록 개선한 함수이다. 마지막으로 aggregate는 그룹별로 함수를 적용한 결과를 반환하는 함수이다.
numeric_cols = sapply(iris[1, ], is.numeric)
print( numeric_cols )
apply(iris[ ,numeric_cols], 2, mean)
aggregate( iris[ , 1:4] ,
list( iris$Species ) , mean )

🌈sqldf패키지
sqldf패키지는 R 자료를 sql문을 통해 핸들링 할 수 있도록 만든 패키지이다.
library(sqldf)
data=iris
sqldf("select Species, count(Species) as cnt from data
natural join
(select `Species`, avg(`Sepal.Length`) as
`Mean.Sepal.Length` from data group by `Species`)
where `Sepal.Length` > `Mean.Sepal.Length`
group by Species")
🌈dplyr, tidyr 패키지
dplyr과 tidyr 패키지는 파이프라인을 통해 효율적이고 직관적으로 연산을 수행할 수 있는 패키지이다.

아래는 sqldf 예제를 dplyr로 해결한 결과이다.
library(dplyr)
data=iris
data%>%
inner_join(data%>%
group_by(Species)%>%
summaise( Mean.Sepal.Length=
mean(Sepal.Length)))%>%
filter(Speal.Length>Mean.Sepal.Length)%>%
group_by(Species)%>%
summarise(cnt =n( ))
library(dplyr)
library(tidyr)
data=iris
melt_df = data %>% gather( key, value, 1:4)
# melt_df = data %>% gather( key, value, -Species)
gather_df=melt_df %>%
group_by(key) %>%
mutate(index=row_number( ))%>%
spread(key, value) %>%
select(-index)
🌈data.table
마지막으로 data.table패키지는 핸들링을 빠르게 처리할 수 있으며, 하나의 백터 내에서 연산하므로 연산과 메모리를 효율적으로 사용할 수 있다는 장점이 있다. 코드가 간결해진다는 장점 또한 가지고 있다.

library(data.table)
data[,lapply(.SD,mean),keyby=.(Species),
.SDcols=-c('Sepal.Length')]
🌈실행속도

참고
RStudio Cheatsheets
Open source and enterprise-ready professional software for data science
