R-由行连接的列字符串的所有成对组合 [英] R - All pairwise combinations of column strings concatenated by the row

查看:70
本文介绍了R-由行连接的列字符串的所有成对组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换这样的数据帧:

How can I transform data frames like this one:

  X__1  X__2  X__3 
  <chr> <chr> <chr>
1 a     b     c    
2 d     e     f    
3 g     h     i    
4 j     k     l  

进入这一个:

  X__1  X__2  X__3 
  <chr> <chr> <chr>
1 a-d   b-e   c-f  
2 a-g   b-h   c-i  
3 a-j   b-k   c-l  
4 d-g   e-h   f-i  
5 d-j   e-k   f-l  
6 g-j   h-k   i-l 

换句话说,它应该对数据帧中的所有行进行所有可能的成对组合,并结合同一列,但用符号(-)分隔。不需要以提及字母的其他顺序重复已经形成的组合,即 ad,be,cf是必需的,而不是 da,eb,fc。

In other words, it should make all possible pairwise combinations of the whole rows in the data frame, combining strings from the same column but separated by a sign(-). It does not need to repeat an already made combination in the other order of mentioning the letter, i.e. "a-d, b-e, c-f" is required but not "d-a, e-b, f-c".

先谢谢您。让我知道如何根据需要改进问题的答案。

Thank you in advance. Let me know how to improve posing the question if needed.

推荐答案

我们可以使用 map

library(purrr)
library(stringr)
map_dfc(df1, combn, m = 2, FUN = str_c, collapse="-")
# A tibble: 6 x 3
#  X__1  X__2  X__3 
#  <chr> <chr> <chr>
#1 a-d   b-e   c-f  
#2 a-g   b-h   c-i  
#3 a-j   b-k   c-l  
#4 d-g   e-h   f-i  
#5 d-j   e-k   f-l  
#6 g-j   h-k   i-l  






或使用摘要/嵌套

library(dplyr)
library(tidyr)
df1 %>%
    summarise(across(everything(), ~ 
        list(combn(., 2, FUN = str_c, collapse="-")))) %>%
    unnest(everything())
# A tibble: 6 x 3
#  X__1  X__2  X__3 
#  <chr> <chr> <chr>
#1 a-d   b-e   c-f  
#2 a-g   b-h   c-i  
#3 a-j   b-k   c-l  
#4 d-g   e-h   f-i  
#5 d-j   e-k   f-l  
#6 g-j   h-k   i-l  






或与 base R

data.frame(lapply(df1, combn, m = 2, paste, collapse="-"))
#   X__1 X__2 X__3
#1  a-d  b-e  c-f
#2  a-g  b-h  c-i
#3  a-j  b-k  c-l
#4  d-g  e-h  f-i
#5  d-j  e-k  f-l
#6  g-j  h-k  i-l



数据



data

df1 <- structure(list(X__1 = c("a", "d", "g", "j"), X__2 = c("b", "e", 
"h", "k"), X__3 = c("c", "f", "i", "l")), class = "data.frame", row.names = c("1", 
"2", "3", "4"))

这篇关于R-由行连接的列字符串的所有成对组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆