VitaBox AD

2022年9月2日 星期五

[R]如何篩選出特定子集數據? subset()

在R語言中,篩選出特定子集數據的函數為subset(),經由查詢Help的結果,其對應的描述和用法如下。顧名思義,利用邏輯符號表述篩選子集的方式,將符合條件的數據子集合篩選出來。

subset():Subsetting Vectors, Matrices and Data Frames

Description:Return subsets of vectors, matrices or data frames which meet conditions.

Usage:subset(x,logical expression,select )


Arguments

x:object to be subsetted.

subset:logical expression indicating elements or rows to keep: missing values are taken as false.

select:expression, indicating columns to select from a data frame.


簡易範例如下,其中x>3 & y !="NA"的意思是將x行中數據大於3同時滿足y行中數據不為NA的數據子集合取出。另外,select=2的意思是將第二行的數據子集合取出,即為y行數據。


x<-c(5:8,1,3)
y<-c(4,3,NA,8,NA,3)
z<-data.frame(x,y)
#範例一
result_1<-subset(z,x>3 & y !="NA")
#範例二
result_2<-subset(z,x>3 & y !="NA",select = 2)

#輸出結果
> z
   x   y
1 5  4
2 6  3
3 7 NA
4 8  8
5 1 NA
6 3  3
> result_1
   x  y
1 5 4
2 6 3
4 8 8
> result_2
    y
1 4
2 3
4 8​

沒有留言:

張貼留言