Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R subset() Function - Data Filtering

R subset() Function - Data Filtering

R Language Examples R Language Examples

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:

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

)

print

(

"Score >= 85:"

)

print

(

high_scores

)

Multiple conditions with AND

print

(

"Beijing and score >= 80:"

)

print

(

subset

(

df

, city

==

"Beijing"

&

Score

=

80

)

)

Filter columns

print

(

"Show only name and score:"

)

print

(

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 R Language Examples