데이터 분석의 순서
1. 데이터 준비, 패키지 준비
2. 데이터 파악
- head(), tail(), View(), dim(), str(), summary등을 이용
- 변수명 수정
- rename(데이터정보, 신규 컬럼명 = 이전 컬럼명) 이름바꾸기
- 파생변수 생성
- ex) mpgcty + mpg$hwy)/2
- ex) mpgtotal >= 20, "pass", "fail")
- mpg의 total이 20보다 크거나 같으면 pass호출 그게아니면 fail호출
ifelse 조건문 활용!
- 빈도 확인
- table(mpg$test) 빈도표
- qplot(mpg$test) 막대그래프
- 조건에 맞는 데이터만 추출하기
- filter() : dplyr패키지 안의 filter를 사용
- ex) exam <- read.csv("파일명")
exam %>% filter(class == 1) 1반인 친구들만 뽑아달라!
library(dplyr)
exam <- read.csv("csv_exam.csv")
exam %>% select(math)
위의 방식처럼 library안의 명령어를 쓰기 때문에
항상 새로운 창에서 시작을 하게되면 library중에
dplyr을 넣어서 인스톨 해준다.
그 후에 exam이라는 변수에 csv파일을 읽어 넣어준다는 의미이다.
exam %>% select(math) 이 구문은 math만 선택해서 들고온다는 의미
exam %>% select(class, math, english)
exam %>% select(-math)
exam %>% filter(class == 1) %>%select(math, english)
exam %>%
filter(class == 1) %>%
select(math, english)
위의 코드들은 순서대로 여러개의 변수를 추출하는법
특정 변수를 제외하는법
filter와 select를 조합해서 사용하는 법
가독성 있게 줄 바꿔서 표현하는 법
exam %>% arrange(math) ## 수학 점수상 오름차순
exam %>% arrange(desc(math)) ## 수학점수 기준 내림 차순
파생변수 추가하기 - mutate()
' 새로만들 변수명과 변수를 만들 때 사용할 공식 입력 '
exam %>%
mutate(total = math + english + science) %>%
head
## 여러 파생변수 한번에 추가하기
exam %>%
mutate(total = math + english + science,
mean = (math + english + science)/3) %>%
head
## mutate() 에 ifelse() 적용
exam %>%
mutate(test = ifelse(science >= 60, "pass", "fail")) %>%
head()
## 추가한 변수를 dplyr 코드에 활용하기
exam %>%
mutate(total = math + english + science) %>%
arrange(desc(total)) %>%
head()
집단별로 요약하기 groub_by, summarise
## 요약하기
exam %>% summarise(mean_math = mean(math))
exam %>%
group_by(class) %>%
summarise(mean_math = mean(math))
# 여러 요약 통계량 한번에 산출하기
exam %>%
group_by(class) %>%
summarise(mean_math = mean(math),
sum_math = sum(math),
median_math = median(math),
n = n())
'
summarise 안에 자주 들어가는 함수들
mean(): 평균
sum() : 합계
sd(): 표준편차
median(): 중앙값
min(): 최솟값
max(): 최댓값
n(): 빈도
'
#mpg 데이터 불러오기
library(ggplot2)
mpg <- as.data.frame(ggplot2::mpg)
head(mpg)
?mpg
# 각 집단별로 다시 집단 나누기
mpg %>%
group_by(manufacturer, drv) %>% # 회사, 구방방식 별 분리 전륜,4륜,후륜
summarise(mean_cty = mean(cty)) %>% # 도심연비 평균
head
# dplyr 조합하기
'dplyr -> 함수를 조합할 때 진가를 발휘한다.'
'회사별로 suv자동차의 도시 및 고속도로 통합 연비 평균을 구해서 내림차순으로 정렬하고, 1~5위까지 출력하기'
mpg %>%
group_by(manufacturer) %>%
filter(class == 'suv') %>%
mutate(total = (cty + hwy)/2) %>%
summarise(mean_total = mean(total)) %>%
arrange(desc(mean_total)) %>%
head(5)
# 데이터 합치기
## 데이터 생성
test1 <- data.frame(id = c(1,2,3,4,5),
midterm=c(60,70,85,90,85))
test2 <- data.frame(id = c(1,2,3,4,5),
final=c(66,76,87,89,80))
test1
test2
# id 기준으로 합치기
total <- left_join(test1, test2, by="id") # by 부분이 기준점
' by에 변수 지정 할 때 겹 따옴표 입력'
total
# 세로로 합치기
group_a <- data.frame(id=c(1,2,3,4,5),
test=c(60,80,76,80,81))
group_b <- data.frame(id=c(6,7,8,9,10),
test=c(70,85,70,81,98))
group_a
group_b
group_all <- bind_rows(group_a, group_b)
group_all
결측치가 있는 행만 제거하는 방법
new_df <- df %>% filter(!is.na(score)) is.na는 NA데이터 즉 결측치 데이터를 들고 오는방법 그 데이터를 부정한다는 ! 를 붙여서 없애는 방법 </br> 여러 변수를 동시에 없애는 방법 new_df <- df %>% filter(!is.na(score) & !is.na(s)) & and연산자를 이용해서 몇개든 함께 없앨수 있다. </br> ※ 결측치가 하나라도 있으면 모두 없애는 방법 이 방법 같은경우 분석에 필요한 데이터가 제거 될수 있기에 신중하게 선택해야한다. new_df <- na.omit(df) 모든 결측치를 없앤다.