R 查找特定元素与其其他列元素的组合

R 查找特定元素与其其他列元素的组合,r,R,我的档案是这样的- Pcol Mcol P1 M1,M2,M5,M6 P2 M1,M2,M3,M5 P3 M4,M5,M7,M6 我想找到Mcol元素与Pcol的组合 预期产量- Pcol Mcol P1 M1,M2 P2 M1,M2 P1 M1,M5 P2 M1,M5 P1 M1,M6 P1 M2,M5

我的档案是这样的-

   Pcol       Mcol
    P1      M1,M2,M5,M6
    P2      M1,M2,M3,M5
    P3      M4,M5,M7,M6
我想
找到Mcol元素与Pcol的组合

预期产量-

Pcol Mcol        
P1  M1,M2        
P2  M1,M2        
P1  M1,M5        
P2  M1,M5        
P1  M1,M6        
P1  M2,M5        
P2  M2,M5        
P1  M2,M6        
P1  M5,M6        
P3  M5,M6        
P2  M1,M3        
P2  M2,M3        
P3  M4,M5        
P3  M4,M7        
P3  M4,M6        
P3  M7,M6        
我试过这个-

x <- read.csv("file.csv" ,header = TRUE, stringsAsFactors = FALSE)
xx <- do.call(rbind.data.frame, 
              lapply(x$Gcol, function(i){
                n <- sort(unlist(strsplit(i, ",")))
                t(combn(n, 2))
              }))

x与您的方法类似,我们可以使用
Map
而不是
lappy
来获取
Pcol
元素

do.call(rbind, Map(function(x, y) data.frame(Pcol=x, Mcol=combn(y, 2, toString)), 
               df$Pcol, strsplit(df$Mcol, ",")))


#   Pcol   Mcol
#1    P1 M1, M2
#2    P1 M1, M5
#3    P1 M1, M6
#4    P1 M2, M5
#5    P1 M2, M6
#6    P1 M5, M6
#7    P2 M1, M2
#8    P2 M1, M3
#9    P2 M1, M5
#10   P2 M2, M3
#11   P2 M2, M5
#12   P2 M3, M5
#13   P3 M4, M5
#14   P3 M4, M7
#15   P3 M4, M6
#16   P3 M5, M7
#17   P3 M5, M6
#18   P3 M7, M6

或者使用
tidyverse

library(tidyverse)

df %>%
  mutate(Mcol = list(combn(str_split(Mcol, ",")[[1]], 2, toString))) %>%
  unnest()

一个选项是用
分隔行
分隔“Mcol”,按“Pcol”分组,获得“值”和
最新的
组合

library(tidyverse)
df1 %>% 
   separate_rows(Mcol) %>% 
   group_by(Pcol) %>% 
   summarise(Mcol = list(combn(Mcol, 2, FUN = toString))) %>%
   unnest
# A tibble: 18 x 2
#   Pcol   Mcol
#   <fct> <chr> 
# 1 P1    M1, M2
# 2 P1    M1, M5
# 3 P1    M1, M6
# 4 P1    M2, M5
# 5 P1    M2, M6
# 6 P1    M5, M6
# 7 P2    M1, M2
# 8 P2    M1, M3
# 9 P2    M1, M5
#10 P2    M2, M3
#11 P2    M2, M5
#12 P2    M3, M5
#13 P3    M4, M5
#14 P3    M4, M7
#15 P3    M4, M6
#16 P3    M5, M7
#17 P3    M5, M6
#18 P3    M7, M6
库(tidyverse)
df1%>%
独立_行(Mcol)%>%
分组依据(Pcol)%>%
总结(Mcol=list(combn(Mcol,2,FUN=toString)))%>%
不耐烦
#一个tibble:18x2
#Pcol Mcol
#     
#1 P1 M1,M2
#2 P1 M1,M5
#3 P1 M1,M6
#4p1m2,M5
#5平方米,6平方米
#6 P1 M5,M6
#7平方米
#8 P2 M1,M3
#9 P2 M1,M5
#10平方米,立方米
#11平方米,5平方米
#12平方米3,5平方米
#13 P3 M4,M5
#14 P3 M4,M7
#15 P3 M4,M6
#16 P3 M5,M7
#17 P3 M5,M6
#18 P3 M7,M6

No,这是频率n,这里我还需要第1列元素