데이터 개념 이해하기¶
벡터 만들기¶
In [1]:
a1 <- c(1,2,3,4,5)
a1
In [2]:
is(a1)
In [3]:
a2 <- c(1L,2L,3L)
a2
In [4]:
is(a2)
In [5]:
a3 <- as.integer(a1)
a3
In [6]:
is(a3)
In [7]:
b <- c(1.23, 3.14, 6.66)
b
In [8]:
c1 <- c('a','b','c','a')
c1
In [9]:
is(c1)
In [10]:
c2 <- c(1,2,3,'z')
c2
In [11]:
is(c2)
In [12]:
# 명목형 벡터로 변환
d1 <- as.factor(c1)
d1
In [13]:
is(d1)
data frame 만들기¶
- 벡터들의 갯수가 같아야 한다
In [14]:
a1 <- c(1,2,3,4,5)
b1 <- c('a','b','c','d','e')
c1 <- c(1.1, 2.2, 3.3, 4.4, 5.5)
In [15]:
df1 <- data.frame(a1, b1, c1)
df1
In [16]:
# 데이터 프레임 이름 설정하기
df2 <- data.frame(count=a1, name=b1,meanCount=c1)
df2
외부 데이터 가져오기 예제¶
In [7]:
# csv 파일 불러오기
df_csv <- read.csv('R-ggagi-data/example_studentlist.csv')
# df_csv <- read.csv('R-ggagi-data/example_studentlist.csv', header=F)
In [10]:
df_csv
In [12]:
# 컬럼 뽑아오기
df_csv$height
In [14]:
#벡터 확인
is.vector(df_csv$height)
In [15]:
# 데이터 프레임 구조 파악
str(df_csv)
In [16]:
# 변수선택 방법 1 (컬럼명)
df_csv$height
In [17]:
# 변수선택 방법 2 (인덱스-R은 인덱싱 1부터)
df_csv[[7]]
In [18]:
# 변수선택 방법 3
df_csv[7]
In [20]:
# 벡터와 데이터프레임 차이를 파악해두기
is(df_csv$height)
is(df_csv[[7]])
is(df_csv[7])
In [24]:
# 여러개의 변수 선택 1 / c 사용
df_csv[c(6,7)]
In [25]:
# 여러개의 변수 선택 2
df_csv[c('bloodtype','height')]
In [28]:
# 행, 열 방식으로 가져오기
# 행은 다 가져오고, 열은 7번째 가져와!
df_csv[,7]
In [30]:
df_csv[2,]
In [31]:
df_csv[2,1]
In [33]:
df_raw2 = df_csv[2,]
In [35]:
df_raw2[1] # 데이터가 아닌 데이터 프레임을 가져옴
In [37]:
df_raw2[[1]] # 데이터만 가져옴
In [47]:
# 데이터만 가져오기
df_csv <- read.csv('R-ggagi-data/example_studentlist.csv', stringsAsFactors = FALSE)
In [48]:
df_csv[2,1]
In [49]:
# 검색 목록
search()
In [64]:
# 검색목록에 추가
attach(df_csv)
In [65]:
# 변수명으로 바로 사용 가능
height
In [66]:
search()
In [67]:
# 검색목록에서 삭제
detach(df_csv)
In [68]:
search()
subset() : 조건으로 변수 선택¶
In [71]:
# 조건으로 변수 선택 subset()
# 키가 170보다 큰 관측치 - subset =
subset(df_csv, subset = (height >170))
select : 변수 선택해서 취하거나 버리기¶
In [73]:
# 특정변수 빼고 보기 - select =
subset(df_csv, select = -height)
In [75]:
# 특정변수 여러개 빼고 보기 - select =
subset(df_csv, select = c(-height, -weight))
colname() : 변수명 바꾸기¶
In [76]:
# 변수명 확인하기
colnames(df_csv)
In [78]:
# 변수명 바꾸기
colnames(df_csv)[6] <- 'blood' # 6번째 변수명 수정
df_csv
In [88]:
# 모든 변수명 바꾸기
df_csv <- read.csv('R-ggagi-data/example_studentlist.csv')
old_list <- colnames(df_csv)
new_list <- c('na','se','ag','gr','ab','bl','he','we')
colnames(df_csv) <- new_list
head(df_csv)
colnames(df_csv) <- old_list
head(df_csv)
cbind() : 새로운 변수 추가¶
In [89]:
bmi <- df_csv$weight/df_csv$height^2
bmi
In [90]:
df_bmi <- cbind(df_csv,bmi)
df_bmi
merge() : 2개의 데이터프레임 합치기¶
In [91]:
df_1 <- read.csv('R-ggagi-data//example_studentlist.csv')
df_2 <- read.csv('R-ggagi-data//omit.csv')
df_1
df_2
In [92]:
df_merge <- merge(df_1, df_2, by='name')
df_merge
rbind() : 행으로 추가하기¶
- 같은 이름의 열을 가지고 있어야 함
In [93]:
df_head <- head(df_merge)
df_tail <- tail(df_merge)
df_head
df_tail
In [94]:
df_rbind <- rbind(df_head, df_tail)
df_rbind
list : 모든 종류의 데이터 객체 담기¶
In [95]:
df <- df_merge
n <- c(1:20)
s <- c('a','b','c')
b <- c(T,F,T,F,T)
tmp_list1 <- list(df,n,s,b,mean)
tmp_list1
In [96]:
# 이름 넣어서 만들기
tmp_list2 <- list(DataFrame=df, Number=n, String=s, Bool=b, Func=mean)
tmp_list2
In [97]:
# 항목 삭제
tmp_list1[1] <- NULL
tmp_list1
In [98]:
# 항목 선택
tmp_list2[2]
tmp_list2['Number']
class() : 자료형 확인¶
- 함수에 인자로 사용 시 주의
In [99]:
class(tmp_list1[1])
class(tmp_list1[[1]])
In [100]:
class(tmp_list2[1])
class(tmp_list2[[1]])
In [101]:
# 여러 개 항목 선택
# list
tmp_list2[c(2,3)]
# list
tmp_list2[c('Number','String')]
# integer
tmp_list2$Number
# character
tmp_list2$String
split()¶
In [104]:
# 성별에 따른 키값을 리스트로 반환
height_sex <- split(df$height, df$sex) # 뒷 값에 따른 앞의 값
height_sex
# 데이터만
height_sex$여자
In [105]:
class(height_sex)
mean() : 리스트 평균 구하기¶
In [106]:
mean(height_sex) # NA 없는 데이터가 있으면 평균을 내지 않는다
mean(height_sex[1])
mean(height_sex[[1]])
sapply() : 리스트 항목별로 작업¶
In [107]:
# 리스트 항목별 평균 mean
height_sex_mean <- sapply(height_sex, mean)
height_sex_mean
height_sex_mean[1]
height_sex_mean[[1]]
In [109]:
# 리스트 항목별 표준편차 sd
height_sex_sd <- sapply(height_sex, sd)
height_sex_sd
height_sex_sd[2]
height_sex_sd[[2]]
In [111]:
# 리스트 항목별 범위 구하기
height_sex_range <- sapply(height_sex, range)
height_sex_range
height_sex_range[1,] # 행
height_sex_range[,1] # 열
명목형 변수 도수분포표 만들기¶
table() : 빈도수¶
In [113]:
# 혈액형별 빈도수 - table()
blood_type_table <- table(df$bloodtype)
blood_type_table
prop.table() : 상대도수¶
In [114]:
# 혈액형별 상대도수 - prop.table()
blood_type_prop_table <- prop.table(blood_type_table)
blood_type_prop_table
rbind() : 함께보기¶
In [115]:
blood_type_rbind <- rbind(blood_type_table, blood_type_prop_table)
blood_type_rbind
addmargins() : table 객체 합 구하기¶
In [155]:
# margin 값은 방향을 나타냄
# margin =1 ->가로방향 (행 방향) / margin= 2 -> 세로방향(칼럼 방향)
blood_type_rbind_sum <- addmargins(blood_type_rbind, margin = 2)
blood_type_rbind_sum
연속형 변수 도수분포표 만들기¶
- 구간을 먼저 나눈다 : 계급
cut() : 구간 나누기¶
In [117]:
# 4개의 구간으로 나누기 - cut()
height_break_4 <- cut(df$height, breaks=4)
height_break_4
In [123]:
head(df$height) # 아래 키가 위에서 나눠진 구간 어디에 속하는지 보여주는 것
In [124]:
# 빈도수 - table()
height_break_4_table <- table(height_break_4)
height_break_4_table
In [125]:
# 상대도수 - prop.table
height_break_4_prop_table <- prop.table(height_break_4_table)
height_break_4_prop_table
In [126]:
# 함께보기 -rbind()
height_break_4_rbind <- rbind(height_break_4_table, height_break_4_prop_table)
height_break_4_rbind
cumsum() : 누적상대도수¶
In [127]:
height_break_4_cumsum <- rbind(height_break_4_rbind, cumsum(height_break_4_rbind[2,]))
height_break_4_cumsum
rownames() : 열 이름 추가/변경¶
In [128]:
rownames(height_break_4_cumsum) <- c('도수','상대도수','누적도수')
height_break_4_cumsum
예제 studentlist2 도수분포표로 만들기¶
In [134]:
student_list2 <- read.csv('R-ggagi-data/example_studentlist2.csv')
#student_list2
In [133]:
# 도수 table()
student_list2_table <- table(student_list2$grade)
student_list2_table
In [136]:
# 상대도수 prop.table
student_list2_porp_table <- prop.table(student_list2_table)
student_list2_porp_table
In [137]:
# 함께보기 rbind
student_list2_rbind <- rbind(student_list2_table, student_list2_porp_table)
student_list2_rbind
In [138]:
# table 객체 합 구하기 addmargins
student_list2_rbind_sum <- addmargins(student_list2_rbind, margin = 2)
student_list2_rbind_sum
In [141]:
# 누적상대도수 cumsum
student_list2_cumsum <- rbind(student_list2_rbind, cumsum(student_list2_rbind[2,]))
student_list2_cumsum
In [144]:
# 열 이름 추가/변경 rownames
rownames(student_list2_cumsum) <- c('도수','상대도수','누적도수')
student_list2_cumsum
분할표 만들기 : 두 변수의 빈도수를 나타내는 표¶
In [147]:
df <- read.csv('R-ggagi-data/example_studentlist.csv')
#df
In [148]:
# 빈도수 구하기 table
sex_blood_table <- table(df$sex, df$bloodtype)
sex_blood_table
In [149]:
# 도수 행, 열 합 구하기 addmargins
addmargins(sex_blood_table)
In [165]:
# margin =1 ->가로방향 (행 방향) / margin= 2 -> 세로방향(칼럼 방향)
addmargins(sex_blood_table, margin=2)
In [167]:
# margin =1 ->가로방향 (행 방향) / margin= 2 -> 세로방향(칼럼 방향)
addmargins(sex_blood_table, margin=1)
In [156]:
# 상대도수 구하기
sex_blood_prop_table <- prop.table(sex_blood_table)
sex_blood_prop_table
In [157]:
# 상대도수 합 구하기
addmargins(sex_blood_prop_table)
In [158]:
# 행별 상대도수 구하기
sex_blood_prop_table_margin_1 <- prop.table(sex_blood_table, margin=1)
sex_blood_prop_table_margin_1
In [159]:
# 열별 상대도수 구하기
sex_blood_prop_table_margin_2 <- prop.table(sex_blood_table, margin=2)
sex_blood_prop_table_margin_2
결측치 NA (값이 없는 경우) 처리¶
- complete.cases() : NA값을 조사해 논리값으로 반환
- na.omit() : 행에 NA가 있으면 행 삭제
In [160]:
a <- c(1,2,3,4,NA,6,7,8,9,10)
complete.cases(a)
In [163]:
# 빼 버려
a[complete.cases(a)]
In [164]:
na.omit(a)
'R' 카테고리의 다른 글
[R] 기술통계 (0) | 2020.07.08 |
---|---|
[R] 데이터 개념 이해하기 (2-2) (0) | 2020.07.08 |
[R] 필수 패키지 설치 및 외부 문서 읽어오기 (0) | 2020.07.02 |
[R] 데이터 개념 이해하기(기초) (0) | 2020.07.02 |
[R] Python 가상환경 생성 및 R 주피터 노트북 연결 (0) | 2020.07.02 |
댓글