2015년 1월 10일 토요일

subset() ; 데이터셋트에서 조건에 맞는 내용을 조회

subset()
Descrition: Return subsets of vectors, matrices or data frames which meet conditions.

Usages subset(dataframe, select, subset)
- dataframe : 조회할 데이터 세트
- select : 열이름
- subset : 조건식

 ex1) iris 데이터의 Species 열에서 Petal.Length > 1.7 데이터를 조회하라

> subset(iris, select = Species, subset=(Petal.Length>1.7))

ex2) iris 데이터에서 Sepal.Width > 3 이고 Petal.Width == 0.2인 Sepal.Length, Petal.Length, Species 열을 조회하라

 > subset(iris, select = c(Sepal.Length, Petal.Length, Species), subset=(c(Sepal.Width > 1.7 & Petal.Width == 0 ))

2014년 12월 23일 화요일

attach() 오브젝트이름을 기억시키는 함수

attach()

Description : The database is attached to the R search path. This means that the database is searched by R when evaluating a variable, so objects in the database can be accessed by simply giving their names.

attach(data셋)을 하면 data에 있는 오브젝트(열값, 속성)이름만으로 값 출력가능

usedcars 데이터의 model값을 접근할려면,

> usedcars$model

로 해야하지만,

> attach(usedcars)를 하면

usedcars에 있는 오브젝트 이름만으로 접근가능

> model

> head(usedcars,10)
   year model price mileage  color transmission
1  2011   SEL 21992    7413 Yellow         AUTO
2  2011   SEL 20995   10926   Gray         AUTO
3  2011   SEL 19995    7351 Silver         AUTO
4  2011   SEL 17809   11613   Gray         AUTO
5  2012    SE 17500    8367  White         AUTO
6  2010   SEL 17495   25125 Silver         AUTO
7  2011   SEL 17000   27393   Blue         AUTO
8  2010   SEL 16995   21026 Silver         AUTO
9  2011   SES 16995   32655 Silver         AUTO
10 2010   SES 16995   36116 Silver         AUTO
> head(usedcars$model, 10)
 [1] "SEL" "SEL" "SEL" "SEL" "SE"  "SEL" "SEL" "SEL" "SES" "SES"
> attach(usedcars)
> head(model, 10)
 [1] "SEL" "SEL" "SEL" "SEL" "SE"  "SEL" "SEL" "SEL" "SES" "SES"

head(usedcars$model,10) 과 head(model,10)은 출력값은 동일

2014년 12월 3일 수요일

구글 스프레드시트로 HTML Parsing 빠르게 하기


=IMPORTHTML("http://dart.fss.or.kr/dsac001/mainY.do", "table", 1)

1. 긁어오고자 하는 웹사이트를 열어 URL 주소를 복사한 후,
2. 구글 드라이브에 로그인해서 만들기 – 스프레드시트를 연 다음,
3. 데이터를 삽입하기 원하는 위치의 가장 왼쪽 위 셀에서 다음과 같은 함수를 입력하면

=ImportHtml("URL", "쿼리", 색인)

 - url : 대상 주소
 - 퀘리 : table, list
 - 색인 : 해당 테이블이 몇번째인가


2014년 12월 1일 월요일

비정형 데이터로 다양한 그래프 그리기

        ## 제주도 여행코스를 검색하여 분석후 그래프로 표시하기
        #
        
        setwd("C:\\Users\\user\\Desktop\\R까기")
        getwd()
        
        library(KoNLP)
        library(wordcloud)
        library(RColorBrewer)
        useSejongDic()
        
        mergeUserDic(data.frame("신비의도로", "ncn"))  # 단어 추가
        mergeUserDic(data.frame("주상절리", "ncn"))  # 단어 추가
        
        
        
        # 1. read txt
        
        txt = readLines("data/Part_1/LEVEL_1/jeju.txt")
        head(txt)
        
        typeof(txt)
        
        # 2. extract nuons
        
        txt_nouns = sapply(txt, extractNoun, USE.NAMES=F)
        
        typeof(txt_nouns)
        
        head(txt_nouns)
        
        # 3. unlist for filtering
        
        txt_nouns_unlist = unlist(txt_nouns)
        
        
        # 4. 두 글자 이상되는것만 필터링
        
        place = Filter(function(x){nchar(x) >=2},txt_nouns_unlist)
        
        
        typeof(place)
        
        head(place,60)
        
        # 5. 필요없는 단어 제거
        
        place = gsub("무난","", place)
        place = gsub("전국","", place)
        place = gsub("렌트카","", place)
        place = gsub("\\d+","", place)
        place = gsub("40","", place)
        place = gsub("입장료","", place)
        place = gsub("관광지","", place)
        place = gsub("대략적","", place)
        place = gsub("어디","", place)
        place = gsub("여행","", place)
        place = gsub("숙소","", place)
        place = gsub("도움","", place)
        place = gsub("연휴","", place)
        place = gsub("할인","", place)
        place = gsub("없구요","", place)
        place = gsub("하시","", place)
        place = gsub("6월4일부터","", place)
        place = gsub("되버려서","", place)
        place = gsub("가격","", place)
        place = gsub("질문","", place)
        place = gsub("모바일할인쿠폰을","", place)
        place = gsub("모바일쿠폰을","", place)
        place = gsub("일정","", place)
        place = gsub("예약","", place)
        place = gsub("제주","", place)
        place = gsub("공항","", place)
        place = gsub("해안","", place)
        place = gsub("이용","", place)
        place = gsub("경우","", place)
        place = gsub("전망","", place)
        place = gsub("코스","", place)
        place = gsub("시간","", place)
        place = gsub("추천","", place)
        place = gsub("일출","", place)
        place = gsub("드라이브","", place)
        place = gsub("도착","", place)
        place = gsub("사진","", place)
        place = gsub("가능","", place)
        place = gsub("박물관","", place)
        place = gsub("바다","", place)
        place = gsub("경유","", place)
        place = gsub("소요","", place)
        place = gsub("하루","", place)
        place = gsub("하게","", place)
        place = gsub("바다","", place)
        place = gsub("녹차","", place)
        place = gsub("위치","", place)
        place = gsub("출발","", place)
        place = gsub("다양","", place)
        place = gsub("랜드","", place)
        place = gsub("바다","", place)
        
        
        # 6. save file
        write(unlist(place), "jeju_2.txt")
        
        # 7. read file as table
        
        
        rev = read.table("jeju_2.txt") # list type
        
        typeof(rev)
        
        
        nrow(rev)
        
        # 8. table 형태로 변환해서 wordcount라는 변수에 할당
        wordcount = table(rev)
        head(sort(wordcount, decreasing=T),30) ## 가장 언급 빈도수가 많은순으로 정렬
        
        
        # 9. pie형으로 보이기 상위 10개
        
        a = head(sort(wordcount, decreasing=T),10)
        windows()
        pie(a)
        savePlot("jeju_2.jpg",type="jpg") # save
        
결과
        # 10. 색상변경
        
        color = rainbow(10)
        pie(a, col=color,radius=1)
        savePlot("jeju_3.jpg",type="jpg") # save
        
결과
    

        # 11. 수치값 넣기
        
        pct = round(a/sum(a)*100,1)
        
        names(a)
        
        typeof(a)
        
        lab = paste(names(a),"\n",pct,"%")
        lab
        
        pie(a, col=color,radius=1, labels=lab, main="제주도 추천 코스")
        
        par(new=T) ## 겹치기?
        
        pie(a, radius=0.6, labels=NA, border=NA, col="white")
        savePlot("jeju_4.jpg",type="jpg") # save

결과
    

        # 12. bar graph
        
        
        bar = head(sort(wordcount, decreasing=T),10)
        
        barplot(bar, main="제주도 추천 코스 TOP 10", col=color,space=0.8, ylim=c(0,25),cex.name=0.7,las=1 )
        # space : 바 간격, ylim : y축 값, cex.name : x축 사이즈, las : 수직/평형
        
        savePlot("jeju_5.jpg",type="jpg") # save
결과
    
        
        
        
        ##13. 수치넣기
        
        bp = barplot(bar, main="제주도 추천 코스 TOP 10", col=color,space=0.8, ylim=c(0,25),cex.name=0.7,las=1 )
        
        pct_bar = round(bar/sum(bar)*100,1)
        pct_bar
        
        barplot(bar, main="제주도 추천 코스 TOP 10", col=color,space=0.8, ylim=c(0,25),cex.name=0.7,las=1)
        
        text(x=bp, y=bar*1.05, labels=paste("(",pct_bar,"%",")"), col="black", cex=0.7)
        text(x=bp, y=bar*0.95, labels=paste(bar,"건"), col="black", cex=0.7)

        savePlot("jeju_6.jpg",type="jpg") # save
        
결과
    

        bp_h = barplot(bar, main="제주도 추천 코스 TOP 10", col=color,space=0.8, xlim=c(0,25),cex.name=0.7,las=1,horiz=T)
        
        text(x=bar*1.15, y=bp_h, labels=paste("(",pct_bar,"%",")"), col="black", cex=0.7)
        
        text(x=bar*0.9, y=bp_h, labels=paste(bar,"건"), col="black", cex=0.7)
        
        
        
        savePlot("jeju_7.jpg",type="jpg") # save
        


결과

2014년 11월 24일 월요일

R round() 반올림 함수

round(x, digits = 0)

x : a numeric vector(실수값)
digits : integer indicating the number of decimal places(round), 반올림된 자리수

* digits = 1 : 소수점 아래 자리
* digits = -1 : 소수점 윗 자리
* digits = 0 : 소수점(원점) 자리

> round(123.456, digits = 1) # 소숫점 아래 첫째자리
[123.5]

> round(123.456, digits = 0) # 소숫점(원점) 자리
[1] 123

> round(123.456, digits= -1) # 소숫점 윗 첫째자리
[1] 120


ex) 100 - 900(단위:100)사이 랜덤 숫자 5개 출력
> round(runif(5, min=100,max=900), digits=-2) # digits = -2 : 둘째 자리까지 표현
[1] 700 500 700 400 300

R apply() 함수

apply() 함수는 복수의 오브젝트에 적용하여 얻은 결과를 벡터나 행렬, 리스트로 반환한다.
apply() 함수를 사용하면 반복문으로 처리해야 할것을 더욱 간결하게 처리할수 있다.

함수기능
apply(X, MARGIN, 함수,…)MARGIN이 1이면 행, MARGIN이 2이면 열에, MARGIN=c(1,2)이면 각 요소에 함수를 적용
lapply(X, 함수,…)벡터, 데이터 프레임, 리스트에 대해 함수를 적용하고 결과를 리스트로 반환
sapply(X, 함수, ,…)결과를 벡터나 행렬로 반환
tapply(X, INDEX, 함수,…)그룹화된 변수에 대해서 그룹별로 함수를 적용하고 교차표를 반환
mapply(함수,…)sapply()의 다변량 버전
sweep(X, MARGIN, 통계량, FUN=”-”,…)벡터와 행렬, 배열의 MARGIN으로 지정한 차원에서 통계량을 뺌(FUN=”+”이면 더함)