我无法以我需要的方式操作数据。采取以下示例数据框:
df <- data.frame(id=factor(c(1,1,1,2,2,3)), person=c('P1','P2','P3','P4','P1','P3'))
id person
1 1 P1
2 1 P2
3 1 P3
4 2 P4
5 2 P1
6 3 P3
我想生成一个数据框,其中包含每个可能的person
对id
,所有唯一排列(即P1
- {{ 1}}和P2
- P2
是唯一的)。例如:
P1
注意:请注意 id person1 person2
1 1 P1 P2
2 1 P1 P3
3 1 P2 P1
4 1 P2 P3
5 1 P3 P1
6 1 P3 P2
7 2 P4 P1
8 2 P1 P4
9 3 P3 NA
&#39; 3&#39;和id
&#39; P3&#39;没有任何其他匹配的人,因此在最终数据框的person
列中有一个NA。虽然这是非常需要的,但如果它不可能或难以置信,我将采取仅忽略person2
3或仅将id
值与其自身匹配的响应(例如{{1} } - P3
)。
如果我不清楚这一点,请告诉我,我很乐意详细说明。谢谢!
答案 0 :(得分:2)
您可以使用merge
作为密钥在df
上id
进行P1-P1
。但是,它会显示与自身匹配的人(例如P2-P2
,# Data in question
df <- data.frame(id=factor(c(1,1,1,2,2,3)),
person=c('P1','P2','P3','P4','P1','P3'))
# Merge with itself
df2 <- merge(df, df, by = "id", suffixes = c("1", "2"), all.x = TRUE)
id person1 person2
1 1 P1 P1
2 1 P1 P2
3 1 P1 P3
4 1 P2 P1
5 1 P2 P2
6 1 P2 P3
7 1 P3 P1
8 1 P3 P2
9 1 P3 P3
10 2 P4 P4
11 2 P4 P1
12 2 P1 P4
13 2 P1 P1
14 3 P3 P3
# Remove self matches
subset(df2, person1 != person2)
id person1 person2
2 1 P1 P2
3 1 P1 P3
4 1 P2 P1
6 1 P2 P3
7 1 P3 P1
8 1 P3 P2
11 2 P4 P1
12 2 P1 P4
等)。您可以在之后删除这些行。
belongs_to :classtypes, :foreign_key => :adtype
belongs_to :classcat, :foreign_key => :cat
答案 1 :(得分:1)
您可以使用merge函数将data.frame合并到自身,如下所示:
new.df=unique(merge(df, df, by='id'))
使用子集函数跟随它以排除两列中具有相同人物的任何内容:
final.df=subset(new.df, person.x!=person.y)