dplyr example

Published by onesixx on

https://www.r-bloggers.com/dplyr-example-1/

 

library(dplyr)
library(FSAdata)

# Biological data for Ruffe captured from the St. Louis River in 1992
# 1992년 4월~10월까지 농어의 생물학적 데이터 
data(RuffeSLRH92)
unique(RuffeSLRH92$indiv)

TABLE <- RuffeSLRH92
str(TABLE)
summary(TABLE)

###################################
## FROM :: 

###################################
## Aggregation & Summarization
## GROUP BY :: filter 
## 집계함수 :: summarize
g1 <- TABLE %>% 
      group_by(month,sex) %>%
      summarize(count=n(),mn_length=mean(length),sd_length=sd(length)) 
g1

###################################
## WHERE :: filter 

# 조건검색 
f1 <- filter(TABLE, sex=="male")
f1 <- droplevels(f1)
xtabs(~sex, data=f1)

# AND조건 조회 
f1 <- filter(TABLE, sex=="male",month<=6)
xtabs(~sex+month, data=f1)

# NOT IN
f1 <- filter(TABLE, sex=="male",!month%in%c(4,5,6))
xtabs(~sex+month, data=f1)

# OR조건 조회 
f1 <- filter(TABLE, sex=="male"|maturity!="ripe")
xtabs(~sex+maturity, data=f1)

###################################
## Add new variables :: mutate()
m1 <- mutate(TABLE, logL=log(length),logW=log(weight))
head(m1)

m1 <- select(TABLE, fish.id,month,day,logL=log(length),logW=log(weight))
head(m1)

###################################
## ORER BY :: arrange
a1 <- arrange(TABLE, month,sex,desc(length))
head(a1);tail(a1)

###################################
## SELECT :: select (columns)

# 특정컬럼 조회 
s1 <- select(TABLE, length,weight)

# 특정컬럼 제외
s1 <- select(TABLE, -fish.id,-indiv,-day,-year)

# 컴럼명 조건 조회 
s1 <- select(TABLE, contains("l"))
head(s1)

 

 

 

 

 

Categories: Reshaping

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x