列表
存储数据的集合 → 有序数据结构
列表&向量:
- 相同点:一维
- 不同点:向量只能存储一种数据类型,列表可以存储多种,甚至列表本身。
mlist()函数 →合并不同数据√
> a <- 1:20
> b <- matrix(1:16,4,4)
> c <- c("This is today's work.")
> mlist <- list(a,b,c)
> mlist
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
[[2]]
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
[[3]]
[1] "This is today's work."
列表的索引/定位
> mlist[1]
$first
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
> mlist[c(1,2)]
$first
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
$second
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
> mlist[1,2]
Error in mlist[1, 2] : incorrect number of dimensions
注意用c()
也可以用先前命的名——同样用c()
> mlist["first","second"]
Error in mlist["first", "second"] : incorrect number of dimensions
> mlist[c("first","second")]
$first
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
$second
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
快捷索引方法——dollar符 $
mlist[1] 和 mlist[[1]] 的区别:
mode将integer和double显示为numeric
umeric, double与integer.
在R中浮点数有两个名字叫numeric与double.
- double是指它的类型(type)名字,numeric是指它的模式(mode)名字,同时也是类(class)的名字。
- mode是指变量的类型如:数值型、字符型、逻辑型等
- class是指变量的类别如:矩阵、列表、数据框等
修改列表都用mlist[[ ]]→两个中括号
> mlist[[3]] <- c("one","two","three") 添加向量✔
> mlist[[-3]] 删除列表❌
Error in mlist[[-3]] : invalid negative subscript in get1index <real>
> mlist[-3] 删除列表✔
> mlist[[3]] <- NULL 删除列表✔