R 对象和类

R 是一种使用对象和类概念的功能性语言。

一个对象只是数据(变量)和方法(函数)的集合。同样,一个类是该对象的蓝图。

让我们举一个现实生活中的例子:

我们可以把类想象成房子的草图(原型)。它包含了关于楼层、门、窗户等的所有细节。基于这些描述,我们建造房子。房子就是对象。


R 中的类系统

虽然大多数编程语言只有一个类系统,但 R 有三个类系统:


R 中的 S3 类

S3 类是 R 编程语言中最流行的类。R 中预定义的大多数类都属于这种类型。

首先,我们创建一个包含各种组件的列表,然后使用 class() 函数创建一个类。例如,

# create a list with required components
student1 <- list(name = "John", age = 21, GPA = 3.5)

# name the class appropriately
class(student1) <- "Student_Info"

# create and call an object
student1

输出

$name
[1] "John"

$age
[1] 21

$GPA
[1] 3.5

attr(,"class")
[1] "student"

在上面的例子中,我们创建了一个名为 student1 的列表,其中包含三个组件。请注意类的创建:

class(student1) <- "Student_Info"

这里,Student_Info 是类的名称。为了创建这个类的对象,我们将 student1 列表传递到 class() 内部。

最后,我们创建了一个 Student_Info 类的对象,并将其命名为 student1

要详细了解 S3 类,请访问 R S3 类


R 中的 S4 类

S4 类是对 S3 类的改进。它们具有正式定义的结构,有助于使同类的对象看起来或多或少相似。

在 R 中,我们使用 setClass() 函数来定义一个类。例如,

setClass("Student_Info", slots=list(name="character", age="numeric", GPA="numeric"))

在这里,我们创建了一个名为 Student_Info 的类,其中包含三个槽(成员变量):nameageGPA

现在要创建一个对象,我们使用 new() 函数。例如,

student1 <- new("Student_Info", name = "John", age = 21, GPA = 3.5)

在这里,在 new() 内部,我们提供了类名 "Student_Info" 和所有三个槽的值。

我们已成功创建了名为 student1 的对象。


示例:R 中的 S4 类

# create a class "Student_Info" with three member variables
setClass("Student_Info", slots=list(name="character", age="numeric", GPA="numeric"))

# create an object of class 
student1 <- new("Student_Info", name = "John", age = 21, GPA = 3.5)

# call student1 object 
student1

输出

An object of class "Student_Info"
Slot "name":
[1] "John"

Slot "age":
[1] 21

Slot "GPA":
[1] 3.5

在这里,我们使用 setClass() 函数创建了一个名为 Student_Info 的 S4 类,并使用 new() 函数创建了一个名为 student1 的对象。

要详细了解 S4 类,请访问 R S4 类


R 中的引用类

与其他两种类相比,引用类是后来引入的。它更类似于我们在其他主要编程语言中常见的面向对象编程。

定义引用类类似于定义 S4 类。我们使用 setRefClass() 函数而不是 setClass()。例如,

# create a class "Student_Info" with three member variables
Student_Info <- setRefClass("Student_Info",
  fields = list(name = "character", age = "numeric", GPA = "numeric"))

# Student_Info() is our generator function which can be used to create new objects
student1 <- Student_Info(name = "John", age = 21, GPA = 3.5)

# call student1 object
student1

输出

Reference class object of class "Student_Info"
Field "name":
[1] "John"
Field "age":
[1] 21
Field "GPA":
[1] 3.5

在上面的例子中,我们使用 setRefClass() 函数创建了一个名为 Student_Info 的引用类。

我们使用生成器函数 Student_Info() 来创建新对象 student1


S3 与 S4 与引用类之间的比较

S3 类 S4 类 引用类
缺少正式定义 使用 setClass() 定义类 使用 setRefClass() 定义类
通过设置类属性创建对象 使用 new() 创建对象 使用生成器函数创建对象
使用 $ 访问属性 使用 @ 访问属性 使用 $ 访问属性
方法属于泛型函数 方法属于泛型函数 方法属于类
遵循复制修改语义 遵循复制修改语义 不遵循复制修改语义
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战