如何创建一个数值向量并判断其类型?

解读

在国内数据岗(金融、医药、互联网、咨询)的面试中,这道题几乎是“必考题”。
面试官想验证三件事:

  1. 你是否真的写过代码,而不是只会背概念;
  2. 你对 R 最底层对象体系(尤其是“向量”这一原子型)有没有直观认识;
  3. 你能否把“创建—检查—确认”三步做得既简洁又符合工程习惯(可重复、可维护、可扩展)。
    很多候选人会直接背出 numeric() 或 c(),但继续追问“双精度与整数如何区分”“typeof/mode/storage.mode/class 返回值差异”就卡壳,因此回答必须体现“严谨 + 全面 + 工程化”。

知识点

  1. 原子向量(atomic vector)是 R 一切对象的基石,数值型细分为 integer 与 double(double 也叫 numeric)。
  2. 创建方式:
    • 拼接函数 c();
    • 生成函数 numeric()、integer()、seq()、:;
    • 强制转换 as.numeric()/as.integer()。
  3. 类型检验函数:
    • typeof() 返回底层 C 类型(最权威);
    • mode() 返回高层模式(历史兼容);
    • storage.mode() 与 typeof() 几乎一致,但在 S 与 C 交互时更细;
    • class() 返回面向对象类属性,对原子向量通常与 typeof 相同,但对因子、Date、POSIXct 等会附加类名;
    • is.*() 系列如 is.numeric()、is.integer()、is.double() 用于布尔判断。
  4. 工程习惯:
    • 用 L 后缀显式声明整数,避免隐式 double;
    • 用 typeof() 做权威断言,用 is.*() 做业务断言;
    • 写自定义断言语数 stopifnot(),确保脚本可重复。

答案

## 1. 创建三种常见数值向量
double_vec <- c(1, 2.3, 4)          # 默认双精度
int_vec    <- c(1L, 2L, 3L)         # 显式整数
seq_vec    <- seq(0, 1, by = 0.1)   # 序列构造

## 2. 判断类型(最严谨写法)
check_type <- function(x) {
  list(
    typeof   = typeof(x),
    mode     = mode(x),
    storage.mode = storage.mode(x),
    class    = class(x),
    is.numeric = is.numeric(x),
    is.integer = is.integer(x),
    is.double  = is.double(x)
  )
}

## 3. 结果展示
check_type(double_vec)
# $typeof  : "double"
# $mode    : "numeric"
# $storage.mode : "double"
# $class   : "numeric"
# $is.numeric : TRUE
# $is.integer : FALSE
# $is.double  : TRUE

check_type(int_vec)
# $typeof  : "integer"
# ...其余略

拓展思考

  1. 因子陷阱:factor(c(1,2,3)) 的 typeof 是 integer,但 is.numeric 为 FALSE;面试常追问“如何把因子转回原始数值”。
  2. 大数据性能:用 integer 可比 double 省 50% 内存,在千万行金融交易表中是优化重点;但整数上限约 2^31-1,溢出会回绕,需用 bit64::integer64。
  3. 类型稳定性:在 Shiny 或 Plumber 部署时,前端 JSON 只认 double,若接口返回整数向量,需显式 as.double() 保证序列化一致性,否则会出现 1 变 1.0 的“看似 bug”的投诉。