r创建与按另一列分组的行元素匹配的新数据框

时间:2018-06-01 09:09:27

标签: r dataframe

我想从下面的df创建一个新数据框。在新数据框(df2)中,df$name中的每个元素都放在第一列中,并在其行中与df$name分组的df$group的其他元素匹配。< / p>

df <- data.frame(group = rep(letters[1:2], each=3),
                 name = LETTERS[1:6])

> df
  group name
1     a    A
2     a    B
3     a    C
4     b    D
5     b    E
6     b    F

在这个例子中,&#34; A&#34;,&#34; B&#34;和&#34; C&#34; df$name中属于&#34; a&#34;在df$group中,我想将它们放在新数据框的同一行中。所需的输出如下所示:

  > df2
          V1   V2
    1     A    B
    2     A    C
    3     B    A
    4     B    C
    5     C    A
    6     C    B
    7     D    E
    8     D    F
    9     E    D
    10    E    F
    11    F    D
    12    F    E

3 个答案:

答案 0 :(得分:2)

我们可以使用base R

merge中执行此操作
out <- setNames(subset(merge(df, df, by.x = 'group', by.y = 'group'),
         name.x != name.y, select = -group), c("V1", "V2"))
row.names(out) <- NULL

out
#   V1 V2
#1   A  B
#2   A  C
#3   B  A
#4   B  C
#5   C  A
#6   C  B
#7   D  E
#8   D  F
#9   E  D
#10  E  F
#11  F  D
#12  F  E

答案 1 :(得分:2)

在我看来,这是自我加入的情况。使用dplyr解决方案可以是:

library(dplyr)    
inner_join(df, df, by="group") %>% 
  filter(name.x != name.y) %>%
  select(V1 = name.x, V2 = name.y)

#    V1 V2
# 1   A  B
# 2   A  C
# 3   B  A
# 4   B  C
# 5   C  A
# 6   C  B
# 7   D  E
# 8   D  F
# 9   E  D
# 10  E  F
# 11  F  D
# 12  F  E

答案 2 :(得分:1)

df <- data.frame(group = rep(letters[1:2], each=3),
                 name = LETTERS[1:6])

library(tidyverse)

df %>%
  group_by(group) %>%                                      # for every group
  summarise(v = list(expand.grid(V1=name, V2=name))) %>%   # create all combinations of names
  select(v) %>%                                            # keep only the combinations
  unnest(v) %>%                                            # unnest combinations
  filter(V1 != V2)                                         # exclude rows with same names

# # A tibble: 12 x 2
#   V1    V2   
#   <fct> <fct>
# 1 B     A    
# 2 C     A    
# 3 A     B    
# 4 C     B    
# 5 A     C    
# 6 B     C    
# 7 E     D    
# 8 F     D    
# 9 D     E    
# 10 F     E    
# 11 D     F    
# 12 E     F