Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

r - Extract elements common in all column groups

I have a R dataset x as below:

  ID Month
1   1   Jan
2   3   Jan
3   4   Jan
4   6   Jan
5   6   Jan
6   9   Jan
7   2   Feb
8   4   Feb
9   6   Feb
10  8   Feb
11  9   Feb
12 10   Feb
13  1   Mar
14  3   Mar
15  4   Mar
16  6   Mar
17  7   Mar
18  9   Mar
19  2   Apr
20  4   Apr
21  6   Apr
22  7   Apr
23  8   Apr
24 10   Apr
25  1   May
26  2   May
27  4   May
28  6   May
29  7   May
30  8   May
31  2   Jun
32  4   Jun
33  5   Jun
34  6   Jun
35  9   Jun
36 10   Jun

I am trying to figure out a R function/code to identify all IDs that exist atleast once in every month. In the above case, ID 4 & 6 are present in all months.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, split the df$ID by Month and use intersect to find elements common in each sub-group.

Reduce(intersect, split(df$ID, df$Month))
#[1] 4 6

If you want to subset the corresponding data.frame, do

df[df$ID %in% Reduce(intersect, split(df$ID, df$Month)),]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...