【问题标题】:How do I write a function to convert a character vector into a character vector of unique pairs of its elements?如何编写一个函数来将字符向量转换为其元素的唯一对的字符向量?
【发布时间】:2019-04-14 10:41:01
【问题描述】:

输入是什么:

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

我想要一个返回的函数:

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

我需要这个函数来单独使用它的输入。我用purrr::map() 和purrr::reduce() 尝试了一些东西,但我没有得到任何有用的东西。

【问题讨论】:

    标签: r purrr stringr


    【解决方案1】:

    我们可以使用来自基础 R 的 combn 和 FUN 参数作为 paste

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

    数据

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

    【讨论】:

    • 完美,甚至不知道combn() 存在!谢谢!
    【解决方案2】:

    不是确切的结果,但也许它可能有用:

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

    结果:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-24
      • 2019-11-21
      • 2012-12-08
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多