데이터 분석/R

앤디 필드의 유쾌한 R 통계학 챕터 3 - R 기초

쎄마비 2022. 3. 31. 15:00
728x90
반응형

 

챕터 3에서는 R 설치와 메뉴 설명 그리고 기초적인 사용 방법을 알려준다.

 

 

# 객체를 만드는 방법
metalica <-c('Lars', 'James', 'Jason', 'Kirk')
metalica

# 객체에서 항목 제외하기
metalica <- metalica[metalica != 'Jason']
metalica

# 객체에 항목 추가하기
metalica <- c(metalica, 'Rob')
metalica


# 작업 디렉토리 설정하기
setwd('C:/Users/Admin/Downloads/andy_field')
getwd()

# 패키지 설치, 불러오기
install.packages('패키지명') # dependencies = TRUE 입력시 의존 패키지도 같이 설치한다
library(패키지명)

# 여러 패키지에 같은 이름의 함수가 있는 경우 함수의 사용방법
패키지명::함수()

# 함수 사용법 확인하기
help(함수명)


# 데이터 프레임 만들기
metalicaNames <- c('Lars', 'James', 'Rob;', 'Kirk')
metalicaAges <- c(47, 47, 48, 46)
metalica <- data.frame(Name = metalicaNames, Age = metalicaAges)
metalica

# 데이터 프레임 활용하기
metalica$Age
metalica$childAge <- c(12, 12, 4, 6)
metalica
names(metalica)

# 기존 변수를 활용하여 새 변수 만들기
metalica$fatherAge <- metalica$Age - metalica$childAge
metalica


# 다양한 변수 만들기

# 문자형
name <- c('Ben', 'Martin', 'Andy', 'Paul', 'Graham', 'Carina', 'Karina', 'Doug', 'Mark', 'Zoe')

# 날짜형
birth_date <- as.Date(c('1977-07-03', '1969-05-24', '1973-06-21', '1970-07-16', '1949-10-10', '1983-11-05', '1987-10-08', '1989-09-16', '1973-05-20', '1984-11-12'))

# 범주형(부호형)
job <- c(rep(1,5),rep(2,5))
job <- factor(job, levels = c(1:2), labels = c('Lecturer', 'Student'))  
job <- gl(2, 5, labels = c('Lecturer', 'Student'))
job

# 변수의 수준 확인하기
levels(job)
levels(job) <- c('Medical lecturer', 'Medical student')

# 수치형
friends <- c(5, 2, 0, 4, 1, 10, 12, 15, 12, 17)
alcohol <- c(10, 15, 20, 5, 30, 25, 20, 16, 17, 18)
income <- c(20000, 40000, 35000, 22000, 50000, 5000, 100, 3000, 10000, 10)
neurotic <- c(10, 17, 14, 13, 21, 7, 13, 9, 14, 13)

lecturerData <- data.frame(name, birth_date, job, friends, alcohol, income, neurotic)
lecturerData


# 자료 가져오기
lecturerData <- read.delim('datafiles/Lecturer Data.dat', header = TRUE)
lecturerData$job <- gl(2, 5, labels = c('Lecturer', 'Student'))
lecturerData


# 자료 저장하기
write.table(lecturerData, 'chapter3.txt', sep='\t', row.names = FALSE)
write.csv(lecturerData, 'champer3.csv')


# 데이터프레임의 일부만 가져오기
lecturerPersonality <- lecturerData[ , c('friends', 'alcohol', 'neurotic')]
lecturerPersonality

lecturerOnly <- lecturerData[job == 'Medical lecturer' , ]
lecturerOnly <- subset(lecturerData, job == 'Medical lecturer')
lecturerOnly

alcoholPersonality <- lecturerData[alcohol > 10, c('friends', 'alcohol', 'neurotic')]
alcoholPersonality <- subset(lecturerData, alcohol > 10, select = c('friends','alcohol', 'neurotic'))
alcoholPersonality

# 매트릭스 만들기
alcoholPeronalityMatrix <- as.matrix(alcoholPersonality)
alcoholPeronalityMatrix <- as.matrix(lecturerData[alcohol > 10, c('friends', 'alcohol', 'neurotic')])
alcoholPeronalityMatrix <- as.matrix(subset(lecturerData, alcohol > 10, select = c('friends','alcohol', 'neurotic')))
alcoholPeronalityMatrix


# 자료를 넓은 형식, 긴 형식으로 상호 변환하기
satisfactionData <- read.delim('datafiles/Honeymoon Period.dat', header = TRUE)
satisfactionStacked <- stack(satisfactionData, select = c('Satisfaction_Base', 'Satisfaction_6_Months', 'Satisfaction_12_Months', 'Satisfaction_18_Months'))
satisfactionStacked

satisfactionUnstacked <- unstack(satisfactionStacked,values ~ind)
satisfactionUnstacked


install.packages('reshape')
library(reshape)

restructedData <- melt(satisfactionData, id = c('Person', 'Gender'), measured = c('Satisfaction_Base', 'Satisfaction_6_Months', 'Satisfaction_12_Months', 'Satisfaction_18_Months'))
restructedData

wideData <- cast(restructedData, Person + Gender ~ variable, value = 'value')
wideData




사용한 함수들

c() == 여러 객체를 합치는 함수
setwd() == set working directory
getwd() == get working directory
data.frame() == data frame 만들기
install.packages() == 패키지 설치하기
library() == 패키지 불러오기
help() == 함수 사용법 확인
as.Date() == 날짜형으로 만들기
factor() == 범주형 데이터 만들기
gl() == 범주형 데이터 만들기
write.table() == 테이블로 내보내기
write.csv() == csv로 내보내기
subset() == 데이터프레임 인덱싱하기
as.Matrix() == 매트릭스로 만들기
read.delim() == 데이터 불러오기
stack() == 넒은 형식으로 펼쳐진 데이터 긴 데이터로 쌓기
unstack() == 긴 데이터로 쌓인 넓은 데이터 펼치기
melt() == 넒은 형식으로 펼쳐진 데이터 긴 데이터로 쌓기
cast() == 긴 데이터로 쌓인 넓은 데이터 펼치기
728x90
반응형