티스토리 뷰

R이 다른 통계 프로그램과 비교해서 가지는 큰 장점 중의 하나는 응용 가능성입니다. 다음의 예시는 구글의 양식을 통해 수집한 설문 조사를 R에서 바로 데이터 프레임으로 읽어들이는 방법입니다. 구글에서 “R read google doc”으로 검색한 결과를 참조하였으며, read.csv에서 인코딩 문제로 한글이 깨지는 문제는 readLines로 해결하였습니다.


<Source>

while (!require(RCurl)) {

  cat("You need to install the library, RCurl\nInstalling...")

  install.packages("RCurl")


# You can fill out the form here!

# https://docs.google.com/forms/d/1l0IWt684mTe-d1RVE05S3Noe-xh47CjO0WL_HEMPv3g/viewform


u="https://docs.google.com/spreadsheet/pub?key=0AmKR51OFQvWqdDNKbjBkQ3NWV1djQlhJek9xS0hxMmc&single=true&gid=0&output=csv"


tc <- getURL(u, ssl.verifypeer=FALSE, .encoding="UTF-8")

tcc <- textConnection(tc, encoding="UTF-8")

  #문제의 코드

  #survey<-read.csv(tcc, encoding="UTF-8") -> 한글 깨짐 문제

survey<-readLines(tcc, encoding="UTF-8")

survey<-survey[-1] # 변수 이름 제외

survey2<-sub(",$",",NA",survey) # 마지막이 ","인 경우는 마지막 설문에 대한 무응답

survey2<-strsplit(survey2,",")

survey2<-unlist(survey2)

surveyDf<-data.frame(matrix(unlist(survey2), ncol=8, byrow=T), stringsAsFactors=T)


is.na(surveyDf$X8) = (surveyDf$X8=="NA")

names(surveyDf)=c("timeStamp","name", "age","gender","height","weight","course","college")


dfSurvey=surveyDf


write.csv(surveyDf, file="survey.csv", row.names=F)


# 결과는 데이터 프레임 dfSurvey 혹은 파일 survey.csv로 확인 가능합니다.




공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함