问题
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
Into this one:
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
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.
回答1:
We can use 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
Or using summarise/unnest
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
Or with 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"))
来源:https://stackoverflow.com/questions/62251966/r-all-pairwise-combinations-of-column-strings-concatenated-by-the-row