你可以使用dplyr:
library(dplyr)
df %>%
left_join(df, by = "groupID", suffix = c("", "_teammate")) %>%
filter(personID != personID_teammate) %>%
select(-personID_teammate, -columnC_teammate)
返回
personID groupID columnA columnB columnC columnA_teammate columnB_teammate
1 1 1 4.162857 2 1 5.492979 18
2 2 2 4.377751 4 0 4.232240 20
3 3 3 4.721330 6 1 6.116825 22
4 4 4 5.372810 8 0 6.111737 24
5 5 5 5.260699 10 1 2.649022 26
6 6 6 4.055667 12 0 2.569150 28
7 7 7 1.913988 14 1 3.810043 30
8 8 8 1.643768 16 0 4.905459 32
9 9 1 5.492979 18 0 4.162857 2
10 10 2 4.232240 20 1 4.377751 4
11 11 3 6.116825 22 1 4.721330 6
12 12 4 6.111737 24 1 5.372810 8
13 13 5 2.649022 26 1 5.260699 10
14 14 6 2.569150 28 1 4.055667 12
15 15 7 3.810043 30 1 1.913988 14
16 16 8 4.905459 32 1 1.643768 16
数据
df <- structure(list(personID = 1:16, groupID = c(1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L), columnA = c(4.1628566514354,
4.37775120677026, 4.72132999511972, 5.37280989644003, 5.2606991455534,
4.05566700843516, 1.91398769391631, 1.6437683999418, 5.49297883127052,
4.23224045206759, 6.11682482265615, 6.11173734702799, 2.64902184119363,
2.5691503674088, 3.81004257186055, 4.90545868691805), columnB = c(2,
4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32), columnC = c(1L,
0L, 1L, 0L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-16L))