728x90

예전에 SAS를 사용할 때, SAS의 가장 큰 강점은 파일 핸들링이었습니다.

R 도 SAS 못지않게 (아니면 더 훌륭한) 파일 핸들링 기능을 갖고 있습니다.

다만 R 에는 여러 패키지들이 있고, 패키지들마다 특징이 있어서, 파일핸들링을 위해 조금 어려운 점이 있었습니다.

패키지 dplyr 을 사용함으로써 SAS에서의 파일 핸들링을 거의 구현할 수 있었습니다.

패키지 dplyr 기능을 엄청 많지만 그 중에서 필수적인 것만을 나열하였습니다.

 

# 1. 변수추출하기 - select( ) 함수

mtcars %>% select(mpg)

mtcars %>% select(mpg, hp, wt)

mtcars %>% select(-mpg)

mtcars %>% select(-mpg,-hp)

# 2. 조건에 맞는 관측치 추출하기 - filter( ) 함수

mtcars

library(plyr)

mtcars %>% filter(am == 0)

mtcars %>% filter(am != 0)

mtcars %>% filter(wt >= 3)

`

# *** 조건에 관측치와 변수 추출하기

mtcars %>% filter(am == 0) %>% select(am, mpg, hp, wt)

mtcars %>% filter(am == 0) %>% select(am,mpg,hp, wt) %>% head

 

# 3. 새로운 변수 만들기 - mutate( ) 함수

mtcars %>% mutate(total = cyl + gear) %>% head

mtcars %>% mutate(tot1 = cyl + gear, tot2= cyl+carb) %>% head

 

# *** 조건에 따른 변수 만들기

mtcars %>% mutate(grade = ifelse(wt >= 3, "big", "small")) %>% head

mtcars %>% mutate(grade = ifelse(wt >= 3,"big","small")) %>% arrange(grade)

# 4. 그룹별 요약하기 - summarise( ) 함수, summarize( ) 함수

mtcars

mtcars %>% summarise(mean_wt =mean(wt))

 

# 5. 그룹별 요약하기 - group_by( ) 함수

mtcars %>% group_by(am) %>% summarise(mean_wt =mean(wt))

m <- mtcars %>% group_by(am) %>% summarise(mean_wt =mean(wt))

class(m)

mtcars %>% group_by(am) %>%

summarise(mean_wt =mean(wt),

sum_mpg =sum(mpg),

n=n())

 

mtcars %>% group_by(am, vs) %>%

summarise(mean_wt =mean(wt),

sum_mpg =sum(mpg),

n=n())

 

# 6. 정렬하기 - arranage( ) 함수

mtcars %>% arrange(wt)

mtcars %>% arrange(desc(wt))

mtcars %>% arrange(am, desc(wt))

+ Recent posts