---
# System prepended metadata

title: object-oriented objects
tags: [S4, R]

---

---
title: 'object-oriented objects'
disqus: hackmd
---

Object-oriented (OO) objects: S4
===

## Table of Contents

[TOC]

## S4：Bioconductor使用的主要結構
```gherkin=1
#使用S4系統時，用setClass來定義一個class
setClass("protein",
    slots = list(sequence="character",
                 species="character")
)
#創建屬於某個class的object時，使用new
sample_protein <- new("protein",
                   sequence="ABCDEFGHIKLMNPQRSTVWXYZ",
                   species="homo sapiens")
 
#S4使用@來subset一個object中的slots
sample_protein@sequence
 
#使用setGeneric來創建generic function
setGeneric("count_sequence_basepair", function(x){standardGeneric("count_sequence_basepair")})
 
#創建後，用setMethod來define這function實際的功能
setMethod("count_sequence_basepair",
c(x = "protein"),
function(x){return(nchar(x@sequence))
})
```

```gherkin=1
#使用
count_sequence_basepair(sample_protein)
#count_sequence_basepair會去抓sample_protein裡面的@sequence
#檢查是不是character然後如果是就會去算nchar
#其中都不會用去到if檢查data type
```

```gherkin=1

```

---
## R6

```gherkin=1
#Reference Class在定義class時後使用setRefClass(),此時也會定義了這個class所具有的method
protein <- setRefClass("protein",
                   fields = list(sequence="character",
                                 species="character")
                    methods=list(
                     count_sequence_basepair = function(){
                        return(nchar(sequence))
                     )
)
#創建object的方式
my_sample <- protein$new(sequence="ABCDEFGHIKLMNPQRSTVWXYZ", species="homo sapiens")
 
#使用method的方式
my_sample$count_sequence_basepair()
[1] 9
&lt;span style="color: #000000;"&gt;

```

```gherkin=1

```


|     | Column 1 | Column 2 | Column 3 |
| --- | -------- | -------- | -------- |
|     |          |          |          |
|     | Text     | Text     | Text     |


| Column 1 | Column 2 | Column 3 |
| -------- | -------- | -------- |
| Text     | Text     | Text     |



###### tags: `R` `S4` 
