开始使用免费开始使用

我的类型是什么?

您刚刚看到 4 个函数,可以帮助您判断当前变量的类型。class()文档)和 typeof()文档)很重要,也会经常用到。mode()文档)和 storage.mode()文档)主要是为了与 S 编程语言保持兼容而存在。

在本练习中,您将查看这些函数对不同变量类型的返回结果。其中包含一些您可能还没遇到过的较少见的类型。

  • array文档):对矩阵的泛化,具有任意维数。
  • formula文档):用于建模和绘图函数,以定义变量之间的关系。

另外请注意,R 中的函数有三类。

  • 您接触到的大多数函数称为 closure
  • 少数重要函数,如 length()文档),称为 builtin 函数,它们使用特殊的求值机制以提升速度。
  • 语言结构,如 if文档)和 while文档)也是函数!它们称为 special 函数。

本练习是课程的一部分

R 中的 S3 与 R6 面向对象编程

查看课程

练习说明

工作区中已预定义 type_info() 函数,用于返回其输入的 class()mode()typeof()storage.mode()。(在控制台输入 type_info 可查看其实现方式。)

  • 创建 some_vars,即编辑器中提供的示例对象列表。
  • 使用 lapply 遍历 some_vars 的各个元素,对每个示例对象调用 type_info(),以查看其类型信息。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Look at the definition of type_info()
type_info

# Create list of example variables
some_vars <- list(
  an_integer_vector = rpois(24, lambda = 5),
  a_numeric_vector = rbeta(24, shape1 = 1, shape2 = 1),
  an_integer_array = array(rbinom(24, size = 8, prob = 0.5), dim = c(2, 3, 4)),
  a_numeric_array = array(rweibull(24, shape = 1, scale = 1), dim = c(2, 3, 4)),
  a_data_frame = data.frame(int = rgeom(24, prob = 0.5), num = runif(24)),
  a_factor = factor(month.abb),
  a_formula = y ~ x,
  a_closure_function = mean,
  a_builtin_function = length,
  a_special_function = `if`
)

# Loop over some_vars calling type_info() on each element to explore them
___
编辑并运行代码