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'
))
}
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
> c2 <- circle(2,20)
> c1
Shape: circle
Radius: 10
> c2Shape: circle
Radius: 20
> area(c1)[1] 314.1593
> area(c2)
> area(c2)
[1] 1256.637
댓글
댓글 쓰기