여정의 기록

[회귀모형]R이란, R함수, 그래프 본문

공부중 .../회귀모형

[회귀모형]R이란, R함수, 그래프

Chelsey 2022. 3. 2. 02:10
728x90

R

- 자료처리, 통계분석, 통계그래프 등 기능을 가진 무료 통계시스템

- 대화형 프로그램 언어

- 객체지향 시스템

 

작업을 할 때는 Working directory를 지정해두면 편리하게 작업이 가능하다.

 

R의 연산함수

상수 : c(1, 2, 3, 4)

제곱근 : x ^ 2

xbar <- sum(weight)/length(weight)

평균 : mean(weight)

가설 검증 함수 : t.test(bml, mu=22.5)

 

c("Hey","hello")

c(T,T,F)

bml > 25 를 통해서 boolean값을 얻을 수 있다.

 

Character 연결 : cat(c("Hey","hello") -> Hey hello

\n 다음 단락으로 넘기는 공백처리 기능 : cat(c("Hey","I am","\n","a cat"))

->  Hey I am

      a cat

 

결측치는 NA로 표시

head(nwd, n=5)

    nwd에서 상단 5개를 출력하시오

rowSums(is.na(nwd)) 

    nwd에 NA값이 있는지? 그것의 row 합은 얼마인지?

colSums(is.na(nwd))

 

na.omit(nwd)

    NA 를 제외한 데이터 출력

 

연속의 값을 생성 seq

    seq(4,9) : 4,5,6,7,8,9

반복하라 rep

    rep( c(3,5), 3) => 3,5,3,5,3,5

    rep( c(3,5), 1:2) => 3, 5, 5

    rep( 1:2, c(3,5)) => 1,1,1,2,2,2,2,2

 

Matrics and arrays

matrix(1:12, nrow=3, byrow=T)

    각 행을 다 채운 다음 그 다음행을 채운다. 

    3행 n열의 형태

역행렬 구하기 solve

    solve(ATA)

%*% : 행렬의 곱

cbind 열 붙이기

    cbind(A=1:4,B=5:8)

    A, B열과 각 열의 값들

rbind 행 붙이기

    rbind(A=1:4,B=5:8)

    A, B행과 각 행의 값들

    붙이고 싶은 데이터를 함수안에 적어주면된다.

factor : 범주형 Categorical variables

fpain <- factor( c(0,1,2,3), levels=0:3)

levels(fpain) <- c("none", "first", "second","third")

여기서 fpain을 출력해보면, levels(fapin)이 적용되어 c(0,1,2,3)값들이 범주화로 정해둔 카테고리로 출력된다.

as.numeric(fpain) 사용시 우리가 정한 숫자가 아닌 1부터 숫자가 범주별로 부여되어 숫자로 카테고리가 출력된다.

Data entry

read.table, read.csv

read.xlsx 를 사용하여 파일 타입별로 적용해 file open한다.

    install.packages("xlsx")

    library(xlsx)

    flower.data=read.xlsx("download/tulip.xlsx",1)

edit(drug,data) -> 스프레드시트로 보여준다.

 

int type -> object type

    factor(명목형), ordered(순서형) 함수

    factor(flower$kind, levels=c(1:3), labels=c("튤립","장미","민들레"))

    ordered(flower$count, levels=c(1:3), labels=c("1개","2개","3개"))

list

object를 하나를 묶는 것

mylist <- list(before=c("하늘","땅"), after=c(10,100))

mylist$before (로 출력)

Data frame

행과 열로 이루어진 데이터 셋

data.frame(flower.kind, flower.count)

Indexing

조건 추리기

Study.sudent[Study.score>60]

    Study 데이터 프레임의 sudent 항목 중, score가 60 이상인 것만 출력

Implicit loops

apply(score, 1, min) : score 에서 1(행) 중 min 최솟값을 구하시오)

    2(열)

lapply (리스트로 표현하는 apply)

sapply (벡터로 표현하는 apply)

tapply (그룹변수별로 표현하는 apply)

Sorting

flower$count[order(flower$count)]


R 그래프

산점도 plot(x, y, pch=2, col="RED")

   pch=2 : 비어있는 세모모양

선그리기 lines(x, y, col="BLUE", lty=2)

   lty==line type=2:점선

 

하나의 산점도 위에

plot(x, y, main="Main title", sub="subtitle", xlab="x-label", ylab="y-label") 를 그리고

text(x, y, "text at (x,y)")  글자를 추가하고

abline(h=x,v=y, lty=2) 선을 추가할 수 있다.

Combining plots

히스토그램 위에 노멀커브를 덧붙일 수 있다.

hist(x, freq=F) # 히스토그램 생성, 만약 그래프가 y높이 때문에 잘린다면 ylim 사용 가능

hist(x, freq=F, ylim=ymax)

curve(dnorm(x), add=T)

 

이를 함수로 만들어 놓으면 쉽게 사용할 수 있다.

hist.normal <- function(x)
{
h <- hist(x,plot=F)
s <- sd(x)
m <- mean(x)
ylim <- range(0, h$density, dnorm(0,sd=s))
hist(x, freq=F, ylim=ylim)
curve(dnorm(x,m,s),add=T)
}

# 실행
source("download/file.r")
x=rnorm(100)
hist.normal(x)

 

 

728x90

'공부중 ... > 회귀모형' 카테고리의 다른 글

[회귀모형]단순회귀모형  (0) 2022.03.04