列表(list)是R的数据类型中最为复杂的一种。一般来说,列表就是一些对象(或成分)的有序集合。列表允许你整合若干对象到单个对象名下。例如,某个列表中可能是若干向量、矩阵、矩阵。数据框,甚至其他列表组合,可以使用list()来创建
list(object1,object2,……)
还可以给列表中的对象命名。
list(name1=object1,name2=object2,……)
- 创建列表
创建一个列表
> g <- 'my first list'
> h <- c(25,26,18,39)
> j <- matrix(1:10,nrow = 5)
> k <- c('one','two','three')
> mylist <- list(g,h,j,k)
> mylist
[[1]]
[1] "my first list"
[[2]]
[1] 25 26 18 39
[[3]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[4]]
[1] "one" "two" "three"
给列表前两个元素添加名称
> mlist <- list(first=g,second=h,j,k)
> mlist
$`first`
[1] "my first list"
$second
[1] 25 26 18 39
[[3]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[4]]
[1] "one" "two" "three"
- 列表的索引
有三种方法可以索引
第一种,标号索引
> mlist[1]
$`first`
[1] "my first list"
> mlist[c(1,4)]#访问两个元素
$`first`
[1] "my first list"
[[2]]
[1] "one" "two" "three"
第二种,名称索引
> mlist$first
[1] "my first list"
> mlist[c('first','second')]
$`first`
[1] "my first list"
$second
[1] 25 26 18 39
第三种,双中括号的索引方式
> mlist[2]
$`second`
[1] 25 26 18 39
> mlist[[2]]
[1] 25 26 18 39
单中括号返回的是列表格式,双中括号返回的事元素本身的属性
可以用class()函数来测试
> class(mlist[2])
[1] "list"
> class(mlist[[2]])
[1] "numeric"
现在知道如何访问列表,就可以对列表中的元素进行修改了
> mlist[5] <- c(1:20)#我们不能直接给列表赋值,因此需要双括号
Warning message:
In mlist[5] <- c(1:20) :
number of items to replace is not a multiple of replacement length
> mlist[[5]] <- c(1:20)
> mlist
$`first`
[1] "my first list"
$second
[1] 25 26 18 39
[[3]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[4]]
[1] "one" "two" "three"
[[5]]
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
若要删除列表中的元素
可以采取负索引的方式。
> mlist[-5]
$`first`
[1] "my first list"
$second
[1] 25 26 18 39
[[3]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[4]]
[1] "one" "two" "three"
也可以给列表元素赋值为空
> mlist[[5]] <- NULL
> mlist
$`first`
[1] "my first list"
$second
[1] 25 26 18 39
[[3]]
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
[[4]]
[1] "one" "two" "three"