레이블이 R인 게시물을 표시합니다. 모든 게시물 표시
레이블이 R인 게시물을 표시합니다. 모든 게시물 표시

2015년 2월 7일 토요일

R 기본 그래프

Base Plotting System

Plotting System

  • base
    헌번에 한개씩 점진적으로 만들어나간다
  • lattice
    자동화가 되어 있어 한번의 펑션콜로 만들어진다
  • ggplot2
    위 두개의 중간 버전 정도 라고 생각하면된다.
  • 3개 중 하나만 골라써야한다.

Base Graphics

  • 플랏을 만들고
  • 이미 존재하는 플랏에 필요한부분을 추가한다.
ex)
plot(x, y)
hist(x)
파라미터가 많고 파라미터의 도움말은 ?파라미터명 으로 볼수있다.

Histogram

library(datasets)
hist(airquality$Ozone)

Scatterplot

library(datasets)
with(airquality, plot(Wind, Ozone))

Boxplot

library(datasets)
#airquality <- transform(airquality, Month = factor(Month))
boxplot(Ozone ~ Month, airquality, xlab = "Month", ylab = "Ozone (ppb)")

중요한 파라미터들

  • par()
    그래픽에 전채적으로 적용되는 파라미터에 대한 설명
    par(“lty”) $ solid
    par(“col”) $ 5.1, 4.1, 4.1, 2.1
    par(“pch”) $11
  • pch
    심볼(기본은 열린 원)
  • lty
    라인 종류(기본 긴줄) etc 점줄 등
  • col
    심볼 색갈 color()를 하면 색 백터를 돌려줌
  • xlab
    x 레이블
  • ylab
    y 레이블
  • las
    레이블들의 방향
  • bg
    배경색깔
  • mar
    마진사이즈
  • oma
    바깥 마진 사이즈(outer margin size) (기본 : 0)
  • mfrow
    number of plots per row, column (plots are filled row-wise)
    multiple plot 을 로우 먼저 채워라
  • mfcol
    number of plots per row, column (plots are filled column-wise)
    multiple plot 을 컬 먼저 채워라

기본 Plotting functions

  • plot
    make scatterplot or other type of plot
  • lines
    n의 점을 잊는 라인을 그린다.
  • points
    플랏에 포인트를 더한다.
  • text
    특정 x,y 좌표에 텍스트를 더한다.(inside plot)
  • title
    x,y labels, title, subtitle, outer margin 등에 주석을 더한다.(out side plot)
  • mtext
    margins(outer or inner)에 쪽에 텍스트를 더한다.
  • axis
    axis 에 ticks/labels 을 더한다.
library(datasets)
with(airquality, plot(Wind, Ozone))
title(main = "Ozone and Wind in New York City")

with(airquality, plot(Wind, Ozone, main = "Ozone and Wind in New York City"))
#add point at above plot
with(subset(airquality, Month == 5), points(Wind, Ozone, col = "blue"))
library(datasets)
#type = n 데이터를 plot에 그리지 말아라
with(airquality, plot(Wind, Ozone, main = "Ozone and Wind in New York City", type = "n"))
with(subset(airquality, Month == 5), points(Wind, Ozone, col = "blue"))
with(subset(airquality, Month != 5), points(Wind, Ozone, col = "red"))
legend("topright", pch = 1, col = c("blue", "red"), legend = c("May", "Other Months"))

기본 선형 회귀 함수 그리기

library(datasets)
with(airquality, plot(Wind, Ozone, main = "Ozone and Wind in New York City", pch = 20))
model <- lm(Ozone ~ Wind, airquality)
#abline 회귀 라인의 슬로프를 보고 펑션에 그린다. lwd 라인 두께
abline(model, lwd = 2)

여러 plot 한번에 뛰우기

library(datasets)
#mflow = multi plot row
par(mfrow = c(1,2))
with(airquality, {
    plot(Wind, Ozone, main = "Ozone and Wind")
    plot(Solar.R, Ozone, main = "Ozone and Solar Radiation")
})
library(datasets)
#mar = margin oma = outer margin
par(mfrow = c(1,3), mar = c (4,4,2,1), oma = c(0, 0, 2, 0))
with(airquality, {
    plot(Wind, Ozone, main = "Ozone and Wind")
    plot(Solar.R, Ozone, main = "Ozone and Solar Radiation")
    plot(Temp, Ozone, main = "Ozone and Temperature")
    #add text at the margin space
    mtext("Ozone And Weather in New York City", outer = TRUE)
})

정리

  • 일단 플랏을 뛰운다.
  • 필요한 요소를 추가한다.
  • 자유롭기는 하지만 설정할게 너무 많다.
​

2015년 1월 29일 목요일

R pivot, R group by order

#R pivot, R group by order

#Grouping 해서 order 한후 원하는 rank뽑아 내기

#문제 x 를 Group으로 그룹핑한 후 각 그룹에 Quantity별로 해당 랭크를 뽑아 나열해라
#  Group Name Quantity
#1     A    v        3
#2     A    u        3
#3     A    w        4
#4     A    x        5
#5     C    x        2
#6     C    y        0

#각 그룹별 2위는?
#답
#  Group Name Quantity
#A     A    w        4
#C     C    y        0

#function is copyed from
#http://stackoverflow.com/questions/14421338/how-do-i-create-order-statistics-by-group-in-r
#author Matthew Plourde

x <- data.frame(Group=c("A","A", "A", "A", "C", "C"),
                Name=c("v", "u", "w","x", "x", "y"),
                Quantity=c(3,3,4,5,2,0))
#  Group Name Quantity
#1     A    v        3
#2     A    u        3
#3     A    w        4
#4     A    x        5
#5     C    x        2
#6     C    y        0

order(x$Quantity, -rank(x$Name))
#[1] 6 5 1 2 3 4
#tail로 뒷 순위에서 부터 랭킹을 가져옴으로 asc로 정렬
in.order <-  function(group) with(group, group[order(Quantity, -rank(Name)), ])
in.order(x)
#  Group Name Quantity
#6     C    y        0
#5     C    x        2
#1     A    v        3
#2     A    u        3
#3     A    w        4
#4     A    x        5

#그냥 적용할 경우 그룹별 랭킹이 나옴
groups.row <- by(x, x$Group, function(group) in.order(group))
groups.row
#x$Group: A
#  Group Name Quantity
#1     A    v        3
#2     A    u        3
#3     A    w        4
#4     A    x        5
#----------------------
#x$Group: C
#  Group Name Quantity
#6     C    y        0
#5     C    x        2

# select 2등
head(tail(groups.row$A,2),1)
#Group Name Quantity
#3     A    w        4

#해당 tail -> head 를 적용
N <- 2
groups.row <- by(x, x$Group, function(group) head(tail(in.order(group),N),1))
#x$Group: A
#  Group Name Quantity
#3     A    w        4
#-----------------------
#x$Group: C
#  Group Name Quantity
#6     C    y        0

#그룹별 랭킹을 하나의 데이터프래임으로 묶기
#rbind(groups.row$A,groups.row$C)
do.call(rbind, groups.row)
#  Group Name Quantity
#A     A    w        4
#C     C    y        0