S3 클래스 - R 객체 지향 예제

원을 객체로 만들어 면적을 구해보자.

#Constructor
circle <- function(id,r) {
  #member
  obj=list(
    id=id,
    r=r
  )
  #class declaration
  class(obj)='circle'
  obj
}
area <- function(x) UseMethod('area',x)
area.circle <- function(x) {
  pi*x$r^2
}
print.circle <- function(x) {
  cat(paste0(
    "Shape: circle\n",
    "Radius: ",x$r,
    '\n'
  ))
}


이제 활용해보자.

> c1 <- circle(1,10)
> c2 <- circle(2,20)
> c1
Shape: circle
Radius: 10
> c2
Shape: circle
Radius: 20
> area(c1)
[1] 314.1593
> area(c2)
[1] 1256.637

댓글

이 블로그의 인기 게시물

R에서 csv 파일 읽는 법

xlwings tutorial - 데이터 계산하여 붙여 넣기