[R] 변수(rename, rm, save, load, paste), qplot, hist, mpg(ggplot2), readxl, dataframe(구조), dplyr(%>%), na.rm
변수
a <- 3
var 1 <- c(1,2,3) # 여러개인 경우 c 로 감싸줘야한다. (c언어), vector type
var2 <- c(1:10) # 1,2,3,4,5,6,7,8,9,10 , python의 range같은거
var3 <- seq(1,5) # 1,2,3,4,5,6,7,8,9,10 , python의 range같은거
var4 <- seq(1,5, by=2) # 1, 3, 5 by=몇 단위로 나타낼 것인가
str1 <- "a"
str2 <- c("a","b","c")
str2 + 2 # error
# 변수명 수정
mpg <- rename(mpg, newname=oldname)
# 변수 제거
rm(str1)
# rda파일을 변수로 저장
save(df, file="df.rda")
rm(df) # 파일을 저장한 변수를 제거할 수 있다.
# 저장해둔 rda파일을 가져와 load하여 사용할 수 있다.
load("df.rda")
한변수의 여러개의 요소 paste로 하나로 만들기
paste(str2, collapse=",") # "a,b,c"
qplot 이용한 count_values() - table() 시각화
qplot(var1)
qplot(mpg$test) # 빈도 막대 그래프 생성
qplot(data=mpg, x=hwy)
qplot(data=mpg, x=drv, y=hwy)
qplot(data=mpg, x=drv, y=hwy, geom="line")
qplot(data=mpg, x=drv, y=hwy, geom="boxplot")
qplot(data=mpg, x=drv, y=hwy, geom="boxplot", colur=drv)
histogram graph
hist(df$total)
mpg 데이터 사용해봅세
library(ggplot2)
mpg <- as.data.frame(ggplot2:mpg)
excel import 패키지
library(readxl)
read_excel("excel_exam.xlsx", col_names=F, sheet=3)
# col_names 열 이름빼고 불러오기
# sheet , excel의 3번 시트 불러오기
read.csv("csv_exam.csv")
write.csv(df, file="df.csv")
dataframe으로 저장하기
english <- c(90,80,60,70)
math <- c(50,60,100,20)
df_midterm <- data.frame(english, math)
df_rename <- rename(df, new_name=old_name)
df$new_col <- df$col1 + df$col2
dataframe 구조 파악
str(dataframe)
# 4 obs : 4개 데이터, 3 variables : 3개 변수
head(df)
head(df, 10)
tail(df)
tail(df, 10)
View(df) # data view 창에서 데이터 확인
dim(df) # shape, 행 열 출력
summary(df) # describe, 요약 통계 출력
table(df$test) # value_conts()
ifelse
ifelse(df$total>0 , "양수", "0 혹은 음수")
library(dplyr)
파이프 라인, 기호 : %>% (command + shift + m)
filter, select, mutate, arrange, summarise, join
dataframe 에 dplyr 사용
filter : filtering 하는 거
# | 혹은 & 사용 가능
df %>% filter(class==1) %>%
filter(math>40)
df %>% filter(class==1 & math>40)
# %in% 연산자
# %in% c() 사용 가능
df %>% filter(class==1 | class==3 | class==5)
df %>% filter(class %in% c(1,3,5))
select : 추출할 열 선택
df %>% select(math) # math 열만 추출
df %>% select(class, math)
df %>% select(-math) # math 열만 빼고 추출
df %>% select(-math, -class)
arrange : sort, 정렬
df %>% arrange(math) # math 기준 오름차순 정렬
df %>% arrange(desc(math)) # math 기준 내림차순 정렬
df %>% arrange(class, math) # class 기준 오름차순 정렬 후 동일한 값은 math 기준 오름차순 정렬
mutate : 새로운 열을 추가
df %>%
mutate(total=math+english+science) %>% # total 이라는 변수 추가
head # 일부 추출
# 혹은 함수 계산한걸 넣을 수도 있다.
df %>%
mutate(mean=(math+english+science_/3) # 평균 만들어서 열 추가
summarise : 그룹별 요약 함수 , (mean, sum, median, n, ... )
data grouping -> 각 group별 분석 -> 결과들을 병합
group_by() : grouping 함수, 인수로 범주형 변수가 들어감(age, gender, ...)
df %>% summarise(mean(math)) # math의 mean 산출
df %>% group_by(class) %>% # class 별로 그룹화
summarise(mean_math = mean(math), # math mean 산출
sum_math = sum(math), # math sum 산출
median_math = median(math), # math median 산출
n = n()) # 행의 개수
join
left_join : id 키 기준으로 합쳐서 total 에 할당
total <- left_join(test1, test2, by="id")
bind_rows : group_a, group_b 를 위 아래로 합친다. dataframe type만 사용가능
bind_rows(group_a, group_b)
inner_joint : 지정한 키에서 동일하게 존재하는 데이터만 추출(교집합)
inner_join(df1, df2) # 자동으로 겹치는 열을 키로 한다.
inner_join(df1, df2, by="name") # 키를 name으로 지정함
base package
rbind :row 기준 합치기(row가 늘어난다) , columns와 변수명이 동일해야함 , 위 아래로 합침
vector, matrix, dataframe... 모두 사용가능
rbind(d1,d2)
cbind : columns 기준 합치기(columns가 늘어난다), row개수가 같아야한다.
cbind(d1,d2)
NA 처리
na.rm=TRUE
sum(res$math) # 데이터 중 NA가 하나라도 있다면 결과는 NA이다.
sum(res$math, na.rm=TRUE) # NA를 제외하고 총합을 낸다.