【问题标题】:Using combn in R to create a matrix of all possible combinations在 R 中使用 combn 创建所有可能组合的矩阵
【发布时间】:2017-02-27 00:11:38
【问题描述】:

这与我正在处理的一个家庭作业问题有关。我需要对几个向量进行数据操作成一个矩阵,TA建议使用combn函数:

# what I'm starting with
a = c(1, 2)
b = c(NA, 4, 5)
c = c(7, 8)

# what I need to get 
my_matrix
a    b    c
1   NA    7
1   NA    8
1    4    7 
1    4    8 
1    5    7 
1    5    8 
2   NA    7 
2   NA    8 
2    4    7 
2    4    8
2    5    7
2    5    8

my_matrix 是一个矩阵,其中包含 a、b 和 c 中元素的所有可能组合,列名为 a、b 和 c。我了解 combn() 在做什么,但不确定如何将其转换为上面显示的矩阵?

提前感谢您的帮助!

【问题讨论】:

  • expand.grid(a = a, b = b, c = c)?
  • 这几乎就像使用 combn 的提示只是分散注意力。谢谢!
  • 提示可能很微妙——?combn 帮助文件在其“另见”部分中提到了expand.grid,其描述为:'用于从所有因素组合创建数据框或向量。'

标签: r data-manipulation


【解决方案1】:

expand.grid,在问题的 cmets 中提到,是更好、更简单的方法。但是你也可以使用combn

#STEP 1: Get all combinations of elements of 'a', 'b', and 'c' taken 3 at a time
temp = t(combn(c(a, b, c), 3))

# STEP 2: In the first column, only keep values present in 'a'
#Repeat STEP 2 for second column with 'b', third column with 'c'
#Use setNames to rename the column names as you want
ans = setNames(data.frame(temp[temp[,1] %in% a & temp[,2] %in% b & temp[,3] %in% c,]),
                                                                  nm = c('a','b','c'))
ans
#   a  b c
#1  1 NA 7
#2  1 NA 8
#3  1  4 7
#4  1  4 8
#5  1  5 7
#6  1  5 8
#7  2 NA 7
#8  2 NA 8
#9  2  4 7
#10 2  4 8
#11 2  5 7
#12 2  5 8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    相关资源
    最近更新 更多