如何在R中获取字符向量的所有可能子集? [英] How to get all possible subsets of a character vector in R?

查看:21
本文介绍了如何在R中获取字符向量的所有可能子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有以下向量:

c("test1","test2","test3")

我正在尝试获取包含以下条目的列表或数据框:

I am trying to get a list or data frame containing the following entries:

"test1" "test2" "test3"
"test1" "test2" NA
"test1" NA "test3"
"test1"  NA NA
NA  "test2" "test3"
NA  "test2" NA
NA  NA "test3"

目标是获取所有可能的子集,而顺序无关紧要,即text1"text2"NA 等效于text2"text1"NA.我非常感谢任何帮助!

The goal would be to get all possible subsets while the order doesn't matter, that is "text1" "text2" NA is equivalent to "text2" "text1" NA. I very much appreciate any help!

推荐答案

可以使用combn:

res <- unlist(lapply(1:3, combn, 
                     x = c("test1","test2","test3"), simplify = FALSE), 
              recursive = FALSE)
res <- sapply(res, `length<-`, 3)
#        [,1]    [,2]    [,3]    [,4]    [,5]    [,6]    [,7]   
#[1,] "test1" "test2" "test3" "test1" "test1" "test2" "test1"
#[2,] NA      NA      NA      "test2" "test3" "test3" "test2"
#[3,] NA      NA      NA      NA      NA      NA      "test3"

这篇关于如何在R中获取字符向量的所有可能子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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