如何使用dplyr从R数据框中过滤某些字符串的列值?
筛选数据可以帮助我们制作所需的数据组,而不是将其进一步用于分析。这样,可以实现精度并且计算变得容易。假设我们有一个同质组,然后根据某些特征对该组进行分区,则可以使用dplyr包的过滤功能。
示例
请看以下数据帧-
> Subject<-rep(c("Stats","Physics","Chemistry","Bio","IT","Marketing"),+ times=c(5,8,7,6,9,5))
> Score<-sample(1:100,40,replace=TRUE)
> df<-data.frame(Subject,Score)
> head(df,20)
Subject Score
1 Stats 88
2 Stats 20
3 Stats 49
4 Stats 31
5 Stats 83
6 Physics 29
7 Physics 43
8 Physics 73
9 Physics 28
10 Physics 74
11 Physics 93
12 Physics 42
13 Physics 73
14 Chemistry 29
15 Chemistry 53
16 Chemistry 70
17 Chemistry 42
18 Chemistry 99
19 Chemistry 10
20 Chemistry 28
加载dplyr软件包-
> library(dplyr)
现在假设我们要过滤主题,如下所示:
> Subject1<-c("Physics","Chemistry")> df %>% filter(Subject %in% Subject1)
Subject Score
1 Physics 29
2 Physics 43
3 Physics 73
4 Physics 28
5 Physics 74
6 Physics 93
7 Physics 42
8 Physics 73
9 Chemistry 29
10 Chemistry 53
11 Chemistry 70
12 Chemistry 42
13 Chemistry 99
14 Chemistry 10
15 Chemistry 28
> Subject2<-c("Stats","Marketing","IT")
> df %>% filter(Subject %in% Subject2)
Subject Score
1 Stats 88
2 Stats 20
3 Stats 49
4 Stats 31
5 Stats 83
6 IT 26
7 IT 70
8 IT 71
9 IT 74
10 IT 10
11 IT 8
12 IT 42
13 IT 62
14 IT 90
15 Marketing 41
16 Marketing 39
17 Marketing 66
18 Marketing 4
19 Marketing 96
> Subject3<-c("Bio")
> df %>% filter(Subject %in% Subject3)
Subject Score
1 Bio 82
2 Bio 96
3 Bio 25
4 Bio 61
5 Bio 47
6 Bio 95
以上是 如何使用dplyr从R数据框中过滤某些字符串的列值? 的全部内容, 来源链接: utcz.com/z/348858.html