1. 자료 가져오기
> setwd(choose.dir()) #대화형으로 폴더를 지정할 수 있음
> getwd()
[1] "C:/Users/amore/Documents/FOR ME/Data Scientist/KNOU/2017년 2학기/고급R활용"
> setwd("C:/Users/amore/Documents/FOR ME/Data Scientist/KNOU/2017년 2학기/고급R활용")
> getwd()
[1] "C:/Users/amore/Documents/FOR ME/Data Scientist/KNOU/2017년 2학기/고급R활용"
> savehistory(file='mywork.Rhistory')
> history()
> history(max.show=10)
2. 다양한 형태의 자료 가져오기
> insurance.data2 = read.table('insurance2.txt', header=T)
> insurance.data2[c(15:16),]
id sex job religion edu amount salary
15 15 m -9 3 4 6 110
16 16 f 1 3 -9 7 88
#-9를 NA로 설정
> insurance.data2 = read.table('insurance2.txt', header=T, na.strings = '-9')
> insurance.data2[c(15:16),]
id sex job religion edu amount salary
15 15 m NA 3 4 6 110
16 16 f 1 3 NA 7 88
> csv.data = read.csv('csv.txt',header=T) #구분자가 콤마
> tab.data = read.table('tab.txt', header=T,sep='\t') #구분자가 탭
> write.table(tab.data, file='C:/Rwork/tab.txt') #Rwork 폴더에 저장
#고정형식 텍스트 파일 읽기
> fwf.data = read.fwf('insurance3.txt',
+ widths=c(2,2,3,3,3,6,6),
+ col.names=c('id','sex','job','religion','edu','amount','salary'))
> fwf.data[fwf.data$job==-9, 'job']=NA
> fwf.data[fwf.data$edu==-9, 'edu']=NA
> fwf.data[fwf.data$salary==-9, 'salary']=NA
> head(fwf.data)
id sex job religion edu amount salary
1 1 m 1 1 3 7.0 110
2 2 m 2 1 4 12.0 135
3 3 f 2 3 5 8.5 127
4 4 f 3 3 5 5.0 150
5 5 m 1 3 3 4.5 113
6 6 m 2 1 2 3.5 95
> fwf2.data = read.fwf('insurance3.txt',
+ widths=c(2,-2,-3,3,3,6,6),
+ col.names=c('id','religion','edu','amount','salary'))
> head(fwf2.data)
id religion edu amount salary
1 1 1 3 7.0 110
2 2 1 4 12.0 135
3 3 3 5 8.5 127
4 4 3 5 5.0 150
5 5 3 3 4.5 113
6 6 1 2 3.5 95
3. 통계 패키지 자료 가져오기
> library(foreign) #spss 파일
> ex1 = read.spss('ex1-1.sav',
+ to.data.frame=T, use.value.labels = T)
Warning message:
In read.spss("ex1-1.sav", to.data.frame = T, use.value.labels = T) :
ex1-1.sav: Unrecognized record type 7, subtype 18 encountered in system file
> ex1
shock response count
1 yes yes 25
2 yes no 19
3 no yes 31
4 no no 141
> dim(ex1)
[1] 4 3
> mouse.data = ex1[rep(1:nrow(ex1),ex1$count),] #가중치
> head(mouse.data)
shock response count
1 yes yes 25
1.1 yes yes 25
1.2 yes yes 25
1.3 yes yes 25
1.4 yes yes 25
1.5 yes yes 25
> dim(mouse.data)
[1] 216 3
> mouse.table=table(mouse.data$shock,mouse.data$response)
> mouse.table
yes no
yes 25 19
no 31 141
> summary(mouse.table)
Number of cases in table: 216
Number of factors: 2
Test for independence of all factors:
Chisq = 27.458, df = 1, p-value = 1.605e-07
- 카이제곱 = 27.458 , p - value = 1.6 X 10마이너스 7승. 자극과 반응간의 유의한 관계가 있음.
4. RData 저장 및 가져오기
> save(ex1, file='c:/Rwork/ex1.Rdata')
> rm(ex1)
> load('C:/Rwork/ex1.Rdata')
> ex1
shock response count
1 yes yes 25
2 yes no 19
3 no yes 31
4 no no 141
> load(file=file.choose()) #대화
참고문헌:
[1] 고급 R 활용 (심송용, 이윤동, 이은경, 김성수 공저, KNOU PRESS)