R 数据类型详解:从基础到实战,附丰富代码实例
2026/7/18 17:52:08 网站建设 项目流程

1. 引言:为什么需要了解 R 数据类型?

R 语言作为统计计算和数据分析的利器,其强大功能建立在丰富而灵活的数据类型体系之上。无论是处理简单的数值向量,还是操作复杂的数据框和列表,对数据类型的深入理解都是高效编程和准确分析的前提。本文将系统介绍 R 中的核心数据类型,并通过大量代码实例展示其特性和应用场景。

2. 基本数据类型(原子向量)

R 中最基础的数据结构是原子向量(atomic vector),所有元素必须是同一类型。以下是 R 的 6 种基本原子类型:

2.1 数值型(numeric)

用于存储整数和浮点数。R 默认将数字视为双精度浮点数。

# 创建数值向量 x <- c(1, 2, 3.5, -4.2) print(x) # 输出: [1] 1.0 2.0 3.5 -4.2 检查类型 class(x) # "numeric" typeof(x) # "double" is.numeric(x) # TRUE 特殊数值 inf_val <- Inf nan_val <- NaN na_val <- NA print(c(inf_val, nan_val, na_val))

2.2 整型(integer)

明确指定为整数的类型,需要在数字后加 L。

# 创建整型向量 int_vec <- c(1L, 2L, 3L, 4L) print(int_vec) # 输出: [1] 1 2 3 4 类型检查 class(int_vec) # "integer" typeof(int_vec) # "integer" is.integer(int_vec) # TRUE 注意:不加L会被当作numeric num_vec <- c(1, 2, 3) is.integer(num_vec) # FALSE is.numeric(num_vec) # TRUE

2.3 字符型(character)

用于存储文本数据,用单引号或双引号包围。

# 创建字符向量 char_vec <- c("apple", "banana", "cherry") print(char_vec) # 输出: [1] "apple" "banana" "cherry" 类型检查 class(char_vec) # "character" typeof(char_vec) # "character" is.character(char_vec) # TRUE 字符串操作 paste("Hello", "World", sep = " ") # 拼接 nchar("R语言") # 字符数(注意中文字符) substr("abcdef", 2, 4) # 提取子串

2.4 逻辑型(logical)

只有 TRUE 和 FALSE 两个值(注意全大写)。

# 创建逻辑向量 logical_vec <- c(TRUE, FALSE, TRUE, FALSE) print(logical_vec) # 输出: [1] TRUE FALSE TRUE FALSE 类型检查 class(logical_vec) # "logical" typeof(logical_vec) # "logical" is.logical(logical_vec) # TRUE 逻辑运算 a <- c(TRUE, FALSE, TRUE) b <- c(FALSE, TRUE, TRUE) a & b # 与运算: FALSE FALSE TRUE a | b # 或运算: TRUE TRUE TRUE !a # 非运算: FALSE TRUE FALSE

2.5 复数型(complex)

用于存储复数,实部和虚部都是数值型。

# 创建复数 comp <- complex(real = c(1, 2), imaginary = c(3, 4)) print(comp) # 输出: [1] 1+3i 2+4i 类型检查 class(comp) # "complex" typeof(comp) # "complex" is.complex(comp) # TRUE 复数运算 comp1 <- 1 + 2i comp2 <- 3 - 4i comp1 + comp2 # 加法: 4-2i comp1 * comp2 # 乘法: 11+2i Mod(comp1) # 模: 2.236068 Arg(comp1) # 辐角: 1.107149

2.6 原始型(raw)

存储原始字节,常用于处理二进制数据。

# 创建原始向量 raw_vec <- as.raw(c(0x48, 0x65, 0x6c, 0x6c, 0x6f)) # "Hello"的ASCII print(raw_vec) # 输出: [1] 48 65 6c 6c 6f 类型检查 class(raw_vec) # "raw" typeof(raw_vec) # "raw" is.raw(raw_vec) # TRUE 转换回字符 char_from_raw <- rawToChar(raw_vec) print(char_from_raw) # 输出: "Hello"

3. 复合数据类型

R 提供了多种复合数据类型,可以存储不同类型的数据。

3.1 向量(vector)

向量是 R 中最基本的数据结构,所有元素必须是同一类型。

# 创建向量 v1 <- c(1, 2, 3, 4, 5) # 数值向量 v2 <- c("a", "b", "c") # 字符向量 v3 <- c(TRUE, FALSE, TRUE) # 逻辑向量 向量化操作(R的核心特性) v1 * 2 # 每个元素乘以2 v1 + c(10, 20, 30, 40, 50) # 向量加法 sqrt(v1) # 每个元素开平方 向量索引 v1[3] # 第三个元素 v1[c(1, 3, 5)] # 第1,3,5个元素 v1[v1 > 2] # 条件索引

3.2 矩阵(matrix)

二维数组,所有元素必须是同一类型。

# 创建矩阵 mat <- matrix(1:12, nrow = 3, ncol = 4) print(mat) # 输出: # [,1] [,2] [,3] [,4] # [1,] 1 4 7 10 # [2,] 2 5 8 11 # [3,] 3 6 9 12 矩阵操作 t(mat) # 转置 mat %*% t(mat) # 矩阵乘法 diag(mat) # 对角线元素 solve(mat[1:2, 1:2]) # 求逆(方阵) 矩阵索引 mat[2, 3] # 第2行第3列 mat[2, ] # 第2行所有列 mat[, 3] # 第3列所有行

3.3 数组(array)

多维数据容器,可以看作多维矩阵。

# 创建三维数组 arr <- array(1:24, dim = c(2, 3, 4)) print(arr) # 输出: # , , 1 # [,1] [,2] [,3] # [1,] 1 3 5 # [2,] 2 4 6 # , , 2 # [,1] [,2] [,3] # [1,] 7 9 11 # [2,] 8 10 12 # ... 共4个二维切片 数组索引 arr[1, 2, 3] # 第1行第2列第3层 arr[1, , ] # 第1行的所有列和层

3.4 因子(factor)

用于存储分类数据,特别适合统计建模。

# 创建因子 gender <- factor(c("男", "女", "男", "女", "男")) print(gender) # 输出: [1] 男 女 男 女 男 # Levels: 男 女 查看因子信息 levels(gender) # 因子水平: "男" "女" nlevels(gender) # 水平数量: 2 table(gender) # 频数统计 有序因子 grade <- factor(c("A", "B", "C", "B", "A"), levels = c("C", "B", "A"), ordered = TRUE) print(grade) 输出: [1] A B C B A Levels: C < B < A

3.5 列表(list)

R 中最灵活的数据结构,可以包含不同类型的元素。

# 创建列表 my_list <- list( name = "张三", age = 25, scores = c(85, 92, 78), passed = TRUE, details = list(city = "北京", job = "数据分析师") ) print(my_list) 输出包含5个元素的列表 列表索引 my_list$name # 使用$按名称访问 my_list[["age"]] # 使用[[]]按名称访问 my_list[[3]] # 使用[[]]按位置访问 my_list$scores[2] # 访问列表中的向量元素 列表操作 length(my_list) # 列表长度 names(my_list) # 元素名称 str(my_list) # 查看结构

3.6 数据框(data.frame)

R 中最常用的数据结构,类似于 Excel 表格或数据库表。

# 创建数据框 df <- data.frame( id = 1:5, name = c("Alice", "Bob", "Charlie", "David", "Eve"), age = c(25, 30, 35, 28, 32), score = c(85.5, 92.0, 78.5, 88.0, 95.5), passed = c(TRUE, TRUE, FALSE, TRUE, TRUE) ) print(df) 输出: id name age score passed 1 1 Alice 25 85.5 TRUE 2 2 Bob 30 92.0 TRUE 3 3 Charlie 35 78.5 FALSE 4 4 David 28 88.0 TRUE 5 5 Eve 32 95.5 TRUE 数据框操作 head(df, 3) # 查看前3行 str(df) # 查看结构 summary(df) # 统计摘要 df$age # 访问age列 df[2, ] # 访问第2行 df[df$score > 90, ] # 条件筛选

4. 特殊数据类型和对象

4.1 日期和时间

# Date类型(日期) today <- Sys.Date() print(today) # 输出: "2026-07-17" 创建日期 dates <- as.Date(c("2026-01-01", "2026-12-31")) print(dates) 日期运算 today + 7 # 7天后 dates[2] - dates[1] # 时间差(天数) POSIXct类型(日期时间) now <- Sys.time() print(now) # 输出: "2026-07-17 10:04:45 CST" 格式化输出 format(now, "%Y年%m月%d日 %H:%M:%S")

4.2 时间序列(ts)

# 创建时间序列 ts_data <- ts(1:24, start = c(2026, 1), frequency = 12) print(ts_data) # 输出: 2026年1月到2027年12月的月度数据 时间序列操作 window(ts_data, start = c(2026, 7), end = c(2026, 12)) # 子集 decompose(ts_data) # 分解趋势、季节、随机成分

4.3 表达式(expression)

# 创建表达式 expr <- expression(x^2 + y^2) print(expr) # 输出: expression(x^2 + y^2) 求值 x <- 3 y <- 4 eval(expr) # 输出: 25 符号微分 D(expression(x^3), "x") # 输出: 3 * x^2

5. 类型检查和转换

5.1 类型检查函数

# 检查具体类型 x <- 10 is.numeric(x) # TRUE is.integer(x) # FALSE(默认是double) is.double(x) # TRUE is.character(x) # FALSE is.logical(x) # FALSE is.complex(x) # FALSE is.raw(x) # FALSE 检查数据结构 vec <- 1:5 is.vector(vec) # TRUE is.matrix(vec) # FALSE is.array(vec) # FALSE is.list(vec) # FALSE is.data.frame(vec) # FALSE 通用类型检查 class(x) # "numeric" typeof(x) # "double" mode(x) # "numeric" storage.mode(x) # "double"

5.2 类型转换函数

# 显式类型转换 as.numeric("123") # 字符转数值: 123 as.character(123) # 数值转字符: "123" as.integer(3.14) # 数值转整数: 3(截断) as.logical(1) # 数值转逻辑: TRUE(0为FALSE,非0为TRUE) as.complex(2) # 数值转复数: 2+0i as.raw(65) # 数值转原始: 41(ASCII的'A') 数据框转换 as.matrix(df) # 数据框转矩阵 as.list(df) # 数据框转列表 as.data.frame(mat) # 矩阵转数据框 因子转换 as.factor(c("A", "B", "A", "C")) # 字符转因子 as.character(gender) # 因子转字符

6. 实战应用示例

6.1 数据清洗中的类型处理

# 模拟脏数据 dirty_data <- data.frame( id = c("001", "002", "003", "004"), age = c("25", "30", "三十五", "28"), # 有非数字字符 income = c("5000", "8000", "6000", "NA"), married = c("TRUE", "FALSE", "TRUE", "FALSE") ) 类型清洗 clean_data <- data.frame( id = as.integer(dirty_data$id), # 字符转整数 age = suppressWarnings(as.numeric(dirty_data$age)), # 转换,非数字变NA income = as.numeric(dirty_data$income), # 字符转数值 married = as.logical(dirty_data$married) # 字符转逻辑 ) print(clean_data) 注意:age列中"三十五"会变成NA

6.2 统计分析中的类型应用

# 创建包含不同类型的数据框 survey <- data.frame( respondent_id = 1:100, gender = factor(sample(c("Male", "Female"), 100, replace = TRUE)), age_group = factor(sample(c("18-25", "26-35", "36-45", "46+"), 100, replace = TRUE), levels = c("18-25", "26-35", "36-45", "46+"), ordered = TRUE), satisfaction = sample(1:5, 100, replace = TRUE), # 1-5分 comments = sample(c("Good", "Average", "Poor", NA), 100, replace = TRUE) ) 按因子分组统计 library(dplyr) survey_summary <- survey %>% group_by(gender, age_group) %>% summarise( avg_satisfaction = mean(satisfaction, na.rm = TRUE), n = n(), .groups = "drop" ) print(survey

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询