R语言中subset函数的用法
1、 测试数据
> df <- data.frame(Age=c(22,24,25,26), Gender=c("Girl","Girl","Boy","Boy"), + City=c("Shanghai","Beijing","Guangzhou","Nanjing")) > df Age Gender City 1 22 Girl Shanghai 2 24 Girl Beijing 3 25 Boy Guangzhou 4 26 Boy Nanjing
2、依据单列过滤数据
> df Age Gender City 1 22 Girl Shanghai 2 24 Girl Beijing 3 25 Boy Guangzhou 4 26 Boy Nanjing > subset(df, Age > 24) ## 依据Age过滤数据 Age Gender City 3 25 Boy Guangzhou 4 26 Boy Nanjing
3、依据多列同时过滤数据
> df Age Gender City 1 22 Girl Shanghai 2 24 Girl Beijing 3 25 Boy Guangzhou 4 26 Boy Nanjing > subset(df,Age <= 25 ) Age Gender City 1 22 Girl Shanghai 2 24 Girl Beijing 3 25 Boy Guangzhou > subset(df,Age <= 25 & Gender == "Girl") ## 指定多列条件进行数据过滤 Age Gender City 1 22 Girl Shanghai 2 24 Girl Beijing
4、依据列筛选的同时,指定要提取的列
> df Age Gender City 1 22 Girl Shanghai 2 24 Girl Beijing 3 25 Boy Guangzhou 4 26 Boy Nanjing > subset(df, Gender == "Girl", select = c("Age","City")) ## 依据gender多虑数据, 同时指定要提取的列 Age City 1 22 Shanghai 2 24 Beijing
来源:https://blog.csdn.net/qq_42458954/article/details/81198729