R subset() Function - Data Filtering
The R subset() function is used to filter data from a data frame based on conditions.
The syntax of subset() is more concise and intuitive than filtering with [ ] square brackets.
The syntax of the subset() function is as follows:
subset(x, subset, select)
Parameter description:
xData frame.
subsetRow filtering condition (logical expression).
selectColumn filtering, can specify which columns to keep.
Example
# Create 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 score >= 85
high_scores <- subset(df, Score>= 85)
print("Score >= 85:")
print(high_scores)
# Multi-condition filtering AND
print("Beijing and score >= 80:")
print(subset(df, City== "Beijing" &Score>= 80))
# Filter columns
print("Only show Name and Score:")
print(subset(df, select = c(Name, Score)))
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 score >= 85
high_scores <- subset(df, Score>= 85)
print("Score >= 85:")
print(high_scores)
# Multi-condition filtering AND
print("Beijing and score >= 80:")
print(subset(df, City== "Beijing" &Score>= 80))
# Filter columns
print("Only show Name and Score:")
print(subset(df, select = c(Name, Score)))
Executing the above code produces the following output:
[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 钱七 90Other extensions
R Language Examples