2014-02-28 2 views
0

다음 상황을 가정 해보십시오. 서로 다른 품질의 데이터가있는 두 개의 테이블이 있습니다. 두 변수 모두 A, B 및 C 변수가 동일합니다. 첫 번째 테이블의 변수는 A1, B1 및 C2이며 두 번째 테이블의 변수는 A2, B2 및 C2입니다.두 벡터의 조합 만들기

첫 번째 테이블을 두 번째 테이블로 업데이트 할 수 있습니다. 6 패턴의 조합이 존재하게된다 :

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 

나는 사람이 모든 가능한 조합을 만들고 나중에 내 함수가 같은 결과를 정리보다 더 간단한 해결책을 알고 있는지 알고 싶습니다.

답변

2

문제를 생각하고있는 중입니다. 그냥 expand.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 
+0

Nice를 사용해주세요. 나는 이것을 얻기 위해'expand.grid'를 45 분 동안 속였습니다. 건배! –

+0

이것은 한 가지 가능성입니다. 그러나 문자를 문자로 반환하는 방법은 무엇입니까? 'expand.grid'는 인자를 반환합니다. –

+0

@Alessandro'expand.grid' 호출에서'stringsAsFactors = FALSE'를 설정하십시오. – Thomas