How do I write a function to convert a character vector into a character vector of unique pairs of its elements?

被刻印的时光 ゝ 提交于 2020-01-24 19:28:08

问题


What the input would be:

c("a", "b", "c")
[1] "a" "b" "c"

I want a function that returns:

[1] "a;b" "a;c" "b;c"

I need this function to work solely off its inputs. I've tried some stuff with purrr::map() andpurrr::reduce(), but I haven't managed to get anything useful.


回答1:


We can use combn from base R with FUN argument as paste

combn(x, 2, FUN = paste, collapse = ";")
#[1] "a;b" "a;c" "b;c"

data

x <- c("a", "b", "c")



回答2:


Not the exact result but maybe it might be useful:

test<-c("a", "b", "c")
lapply(test,function(x) paste0(x,";",setdiff(test,x)))

Result:

[[1]]
[1] "a;b" "a;c"

[[2]]
[1] "b;a" "b;c"

[[3]]
[1] "c;a" "c;b"


来源:https://stackoverflow.com/questions/55674350/how-do-i-write-a-function-to-convert-a-character-vector-into-a-character-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!