數(shù)據(jù)框的下標(biāo)與子集的提取
數(shù)據(jù)框的下標(biāo)與子集的提取與矩陣基本相同. 不同的是: 對(duì)于列我們可以使用變量的名稱, 仍以數(shù)據(jù)集Puromycin進(jìn)行舉例說(shuō)明.
?1、提取單個(gè)元素
> Puromycin[1, 1]
[1] 0.02
2、提取一個(gè)子集,例如第1, 3, 5行,第1, 3列
> Puromycin[c(1, 3, 5), c(1, 3)]
conc state
1 0.02 treated
3 0.06 treated
5 0.11 treated
> Puromycin[c(1, 3, 5), ]
conc rate state
1 0.02 76 treated
3 0.06 97 treated
5 0.11 123 treated
常使用變量名稱來(lái)指定列的位置,上面的命令等價(jià)于
> Puromycin[c(1, 3, 5), c("conc", "state")]]
3、提取一列(變量的值). 一個(gè)數(shù)據(jù)框的變量對(duì)應(yīng)了數(shù)據(jù)框的一列, 如果變量有名稱, 則可直接使用“數(shù)據(jù)框名$變量名”這種格式指向?qū)?yīng)的列. 例如
> Puromycin$conc # 等價(jià)于 Puromycin[,1]
[1] 0.02 0.02 0.06 0.06 0.11 0.11 0.22 0.22 0.56 0.56
[11] 1.10 1.10 0.02 0.02 0.06 0.06 0.11 0.11 0.22 0.22
[21] 0.56 0.56 1.10
> Puromycin$state
[1] treated treated treated treated treated
[6] treated treated treated treated treated
[11] treated treated untreated untreated untreated
[16] untreated untreated untreated untreated untreated
[21] untreated untreated untreated
Levels: treated untreated
4、提取滿足條件的子集
> subset(Puromycin, state == "treated" & rate > 160)
conc rate state
9 0.56 191 treated
10 0.56 201 treated
11 1.10 207 treated
12 1.10 200 treated
> subset(Puromycin, conc > mean(conc))
conc rate state
9 0.56 191 treated
10 0.56 201 treated
11 1.10 207 treated
12 1.10 200 treated
21 0.56 144 untreated
22 0.56 158 untreated
23 1.10 160 untreated
下期請(qǐng)期待在數(shù)據(jù)框中添加新變量








暫無(wú)數(shù)據(jù)