R subset() Function - Data Filtering
The R subset() function is used to filter data from a data frame by conditions.
The syntax of subset() is more concise and intuitive than filtering with [ ] brackets.
The syntax of the subset() function is as follows:
subset(x, subset, select)
Parameter Description:
-
x A data frame.
-
subset A row filtering condition (a logical expression).
-
select Column filtering, specifying which columns to keep.
Example
Create a data frame
df
<-
data.frame
(
Name
=
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
,
"Zhao Liu"
,
"Qian Qi"
)
,
Age
=
c
(
25
,
30
,
28
,
35
,
22
)
,
Score
=
c
(
88
,
92
,
76
,
85
,
90
)
,
City
=
c
(
"Beijing"
,
"Shanghai"
,
"Beijing"
,
"Guangzhou"
,
"Shanghai"
)
,
stringsAsFactors
=
FALSE
)
Filter students with scores >= 85
high_scores
<-
subset
(
df
, score
=
85
)
(
"Score >= 85:"
)
(
high_scores
)
Multiple conditions with AND
(
"Beijing and score >= 80:"
)
(
subset
(
df
, city
==
"Beijing"
&
Score
=
80
)
)
Filter columns
(
"Show only name and score:"
)
(
subset
(
df
, select
=
c
(
Name, score
)
)
)
The output of the code above is:
[1] "成绩 >= 85:"
姓名 年龄 成绩 城市
1 张三 25 88 北京
2 李四 30 92 上海
4 赵六 35 85 广州
5 钱七 22 90 上海
[1] "北京且成绩 >= 80:"
姓名 年龄 成绩 城市
1 张三 25 88 北京
[1] "只显示姓名和成绩:"
姓名 成绩
1 张三 88
2 李四 92
3 王五 76
4 赵六 85
5 钱七 90
R Language Examples