R中的子集数据

时间:2014-12-30 16:57:45

标签: r

假设我们有两个变量x1和x2,我需要对x1 = {a,b,c,d}

的数据进行子集化
mydata <- data.frame(x1=c("a","b","c","n","a","d","b","l","a","c","t","a","b","d","c","l","n","b"), x2=c(1,3,5,2,0,5,4,6,2,9,2,6,0,6,1,2,6,6))
    x1  x2
1   a   1
2   b   3
3   c   5
4   n   2
5   a   0
6   d   5
7   b   4
8   l   6
9   a   2
10  c   9
11  t   2
12  a   6
13  b   0
14  d   6
15  c   1
16  l   2
17  n   6
18  b   6

1 个答案:

答案 0 :(得分:3)

您可以使用%in%

> mydata[mydata$x1 %in% c("a", "b", "c", "d"), ]
   x1 x2
1   a  1
2   b  3
3   c  5
5   a  0
6   d  5
7   b  4
9   a  2
10  c  9
12  a  6
13  b  0
14  d  6
15  c  1
18  b  6

还有subset功能:

subset(mydata, subset = x1 %in% c("a", "b", "c", "d"))