list列表
> mylist <- list(stud.id = 1234,
+ stud.name = "Tom",
+ stud.marks = c(12, 3, 14, 25, 19))
> mylist
$stud.id
[1] 1234
$stud.name
[1] "Tom"
$stud.marks
[1] 12 3 14 25 19
注意双括号和单括号,及$
符号的取值结果
> mylist[[1]]
[1] 1234
> mylist[1]
$stud.id
[1] 1234
> mylist$stud.id
[1] 1234
> mylist$stud
NULL
注意双括号和单括号
> mode(mylist[[1]])
[1] "numeric"
> mode(mylist[1])
[1] "list"
> names(mylist)
[1] "stud.id" "stud.name" "stud.marks"
> names(mylist) <- c("id", "name", "marks")
> names(mylist)
[1] "id" "name" "marks"
> mylist
$id
[1] 1234
$name
[1] "Tom"
$marks
[1] 12 3 14 25 19
例如对mylist
添加父母的名字这一新项:
> length(mylist)
[1] 3
> mylist$parents <- c("mna", "Jutice")
> mylist
$id
[1] 1234
$name
[1] "Tom"
$marks
[1] 12 3 14 25 19
$parents
[1] "mna" "Jutice"
> length(mylist)
[1] 4
如删除列表中的第3个成绩分数成分:(相当于先提取list的[-3]数据,即除了第3项的其他数据,再进行重新赋值)
> mylist <- mylist[-3]
> mylist
$id
[1] 1234
$name
[1] "Tom"
$parents
[1] "mna" "Jutice"
如新建一个other
列表,将其与前面的mylist
列表合并:
> other <- list(age=19, sex="male")
> other
$age
[1] 19
$sex
[1] "male"
> newlist <- c(mylist, other)
> newlist
$id
[1] 1234
$name
[1] "Tom"
$parents
[1] "mna" "Jutice"
$age
[1] 19
$sex
[1] "male"
unlist(list)
将list列表转换成向量> unlist(newlist)
id name parents1 parents2 age sex
"1234" "Tom" "mna" "Jutice" "19" "male"
注:转换后的向量与普通向量有所不同,不同之处在于该向量的每个元素都有一个名字和值,类似与python字典中的key
和value
。
> p <- unlist(newlist)
> p
id name parents1 parents2 age sex
"1234" "Tom" "mna" "Jutice" "19" "male"
> p[2]
name
"Tom"
> p[[2]]
[1] "Tom"
> p$name
Error in p$name : $ operator is invalid for atomic vectors