如何根據數值列和類別列對 R 資料框進行子集選擇?


子集選擇是一種常用的技術,根據分析目標的不同,它可以用於許多不同的目的。為了使用 dplyr 包排除一列來對資料框進行子集選擇,我們可以按照以下步驟操作:

  • 建立資料框。
  • 同時根據數值列和類別列對資料框進行子集選擇,使用 dplyr 包中的 filter 函式。

建立資料框

讓我們建立一個如下所示的資料框:

 即時演示

Level<-sample(c("Low","Medium","High"),20,replace=TRUE)
Score<-sample(1:10,20,replace=TRUE)
Dat<-data.frame(Level,Score)
Dat

執行上述指令碼後,將生成以下輸出(由於隨機化,此輸出在您的系統上可能會有所不同):

  Level Score
1 High   4
2 Low    7
3 High   1
4 Medium 6
5 Medium 10
6 High   9
7 High 9
8 Low 3
9 Low 3
10 High 4
11 Low 5
12 Medium 3
13 High 8
14 High 10
15 High 5
16 Low 8
17 High 10
18 High 7
19 Low 10
20 Low 6

基於數值列和類別列進行子集選擇

載入 dplyr 包並對 Dat 進行子集選擇,其中 Score 列大於 5 且 Level 等於 Low:

library(dplyr)
Level<-sample(c("Low","Medium","High"),20,replace=TRUE)
Score<-sample(1:10,20,replace=TRUE)
Dat<-data.frame(Level,Score)
Dat%>%filter(Score>5,Level=="Low")

輸出

 Level Score
1 Low 7
2 Low 8
3 Low 10
4 Low 6

更新於: 2021年8月13日

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告