如何在R中根據字元列的水平建立子集?


在 R 程式設計中,大多數具有字串值的列可以用字元資料型別或因子資料型別表示。例如,如果我們有一列 Group,它有四個唯一值 A、B、C 和 D,那麼它可以是字元或因子,具有四個水平。如果我們想要獲取這些列的子集,則可以使用子集函式。請檢視下面的示例。

考慮以下資料框 -

示例

set.seed(888)
Grp<-sample(c("A","B","C"),20,replace=TRUE)Age<-sample(21:50,20)
df1<-data.frame(Grp,Age)
df1

輸出

   Grp  Age
1   A   35
2   C   40
3   C   48
4   C   46
5   C   36
6   C   33
7   B   47
8   A   45
9   B   43
10  B   37
11  B   30
12  A   24
13  C   39
14  C   50
15  C   25
16  A   34
17  B   49
18  A   44
19  C   38
20  B   26

str(df1) 'data.frame': 20 obs. of 2 variables

$ Grp: chr "A" "C" "C" "C" ...
$ Age: int 35 40 48 46 36 33 47 45 43 37 ...

根據 Grp 列值 A 和 C 獲取 df1 的子集 -

示例

subset(df1, Grp %in% c("A","C"))

輸出

Grp Age
1 A 35
2 C 40
3 C 48
4 C 46
5 C 36
6 C 33
8 A 45
12 A 24
13 C 39
14 C 50
15 C 25
16 A 34
18 A 44
19 C 38

讓我們看看另一個例子 -

示例

 即時演示

Class<-sample(c("First","Second","Third","Fourth"),20,replace=TRUE)
Score<-sample(1:10,20,replace=TRUE)
df2<-data.frame(Class,Score)
df2

輸出

   Class  Score
1  First   10
2  First   3
3  First   1
4  First   7
5  First   1
6  Third   4
7  First   3
8  First   3
9  Second  2
10 First   8
11 Fourth  1
12 Third   6
13 First   6
14 Second  1
15 First   8
16 Fourth  4
17 Third   7
18 Fourth  4
19 Third   7
20 Fourth  1

str(df2) 'data.frame': 20 obs. of 2 variables

$ Class: chr "First" "Third" "Second" "First" ...
$ Score: int 1 4 9 8 9 10 2 8 5 8 ...

根據 Class 列值 First 和 Fourth 獲取 df2 的子集 -

示例

subset(df2, Class %in% c("First","Fourth"))

輸出

Class Score
1 First 1
4 First 8
5 First 9
6 Fourth 10
7 Fourth 2
9 Fourth 5
10 Fourth 8
11 Fourth 8
13 Fourth 7
14 Fourth 10
15 First 7
16 Fourth 10
17 Fourth 4
19 First 2
20 First 10

更新於: 2020年10月9日

1K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.