R语言笔记第四课-列表和数据框

# ------------ 第六章 列表和数据框
# R中list是一个以对象的有序集合构成的对象

Lst <- list(name="xiaoran",wife="libingbing",no.children=3,child.agres=c(4,7,9))
$name
[1] "xiaoran"

$wife
[1] "libingbing"

$no.children
[1] 3

$child.agres
[1] 4 7 9

# 通过下标直接访问
Lst[[1]]  
Lst[["name"]]

output : "xiaoran"

Lst[4]
Lst[[4]]
Lst$child.agres
4 7 9

Lst$child.agres[1]
Lst[[4]][1]
4

x <- "name"; Lst[[x]]
"xiaoran"

# Lst[[1]] 和Lst[1] 的差别。[[. . . ]] 是用来选择单个元素
# 的操作符,而[. . . ] 是一个更为一般的下标操作符。因此前者得到的是列表Lst 中的
# 第一个对象, 并且含有分量名字的命名列表(named list)中的分量名字会被排除在外
# 的 1 。后者得到的则是列表Lst 中仅仅由第一个元素构成的子列表。如果是命名列表,
# 分量名字会传给子列表的。

# 为列表增加一个分量
Lst[4] <- list(matrix=array(1:9,dim=c(3,3)))


list.A <- list(A=c(1,2),"Aname"="A")
list.B <- list(B=c(1,2),"Aname"="B")
list.C <- list(C=c(1,2),"Aname"="C")
# 列表连接
list.ABC <- c(list.A, list.B, list.C)
list.ABC
$A
[1] 1 2
$Aname
[1] "A"

$B
[1] 1 2
$Aname
[1] "B"

$C
[1] 1 2
$Aname
[1] "C"

# ------数据框
# 数据框常常会被看作是一个由不同模式和属性的列构成的矩阵。它能以矩阵形式
# 出现,行列可以通过矩阵的索引习惯访问。
# 符合数据框限制的列表可被函数as.data.frame() 强制转换成数据框

name <- c("A","B","C","D")
source <- c(100,99,98,97)
level <- c(1,2,1,3)

myDataFrame <- data.frame(names = name, source = source, level=level)
out:
names source level
1     A    100     1
2     B     99     2
3     C     98     1
4     D     97     3

myDataFrame$name
myDataFrame[["names"]]
A B C D


myDataFrame[1:2]
names source
1     A    100
2     B     99
3     C     98
4     D     97

你可能感兴趣的:(R语言笔记)