R 创建两个向量的组合

R 创建两个向量的组合,r,R,假设以下情况。有两个表,每个表都有不同质量的数据。它们都有相同的变量A、B和C。第一个表中的变量称为A1、B1和C2,而第二个表中的变量称为A2、B2和C2 可以使用第二个表更新第一个表。有六种可能的组合: A1、B1、C2 A1、B2、C1 A2、B1、C1 A1、B2、C2 A2、B1、C2 A2、B2、C1 问题是如何在R中获得它。我使用的是以下内容: require(utils) require(stringr) vars <- c("A1", "B1", "C1", "A2",

假设以下情况。有两个表,每个表都有不同质量的数据。它们都有相同的变量A、B和C。第一个表中的变量称为A1、B1和C2,而第二个表中的变量称为A2、B2和C2

可以使用第二个表更新第一个表。有六种可能的组合:

A1、B1、C2

A1、B2、C1

A2、B1、C1

A1、B2、C2

A2、B1、C2

A2、B2、C1

问题是如何在R中获得它。我使用的是以下内容:

require(utils)
require(stringr)

vars <- c("A1", "B1", "C1", "A2", "B2", "C2")

combine <- function(data, n){
  com1 = combn(data, n)# make all combinations
  com2 = c(str_sub(com1, end=-2L))# remove the number in the end of the name
  com3 = matrix(com2, nrow = dim(com1)[1], ncol = dim(com1)[2])# vector to matrix
  com3 = split(com3, rep(1:ncol(com3), each = nrow(com3)))# matrix to list
  com3 = lapply(com3, duplicated)# find list elements with duplicated names
  com3 = lapply(com3, function(X){X[which(!any(X == TRUE))]})# identify duplicated names
  pos = which(as.numeric(com3) == 0)# get position of duplicates
  com3 = com1[,pos]# return elements from the original list
  com3 = split(com3, rep(1:ncol(com3), each = nrow(com3)))# matrix to list
  com3 = lapply(com3, sort)# sort by alphabetical order
  com3 = as.data.frame(com3, stringsAsFactors = FALSE)# matrix to data frame
  res = list(positions = pos, combinations = com3)# return position and combinations
  return(res)
}
combine(vars, 3)

$positions
[1]  1  4  6 10 11 15 17 20

$combinations
  X1 X2 X3 X4 X5 X6 X7 X8
1 A1 A1 A1 A1 A2 A2 A2 A2
2 B1 B1 B2 B2 B1 B1 B2 B2
3 C1 C2 C1 C2 C1 C2 C1 C2
require(utils)
要求(stringr)

vars你对这个问题考虑得太多了。只需使用
展开.grid

> expand.grid(c('A1','A2'),c('B1','B2'),c('C1','C2'))
  Var1 Var2 Var3
1   A1   B1   C1
2   A2   B1   C1
3   A1   B2   C1
4   A2   B2   C1
5   A1   B1   C2
6   A2   B1   C2
7   A1   B2   C2
8   A2   B2   C2

美好的为了得到这个,我在
expand.grid
上混了45分钟。干杯这是一种可能性。但是如何将字符作为字符返回呢?请注意,
expand.grid
返回因子。@Alessandro在
expand.grid
调用中设置
stringsAsFactors=FALSE