2012-05-28 5 views
0

는 다음 행렬을 고려해트라이어드를 쌍으로 재조합합니까?

sequence <- structure(list(C1 = c(2L, 9L, 3L, 9L, 1L, 8L, 9L, 6L, 4L, 5L, 
3L, 2L), C2 = c(3L, 6L, 5L, 8L, 8L, 7L, 3L, 7L, 2L, 1L, 4L, 1L 
), C3 = c(8L, 2L, 6L, 4L, 6L, 5L, 7L, 4L, 5L, 9L, 1L, 7L)), .Names = c("C1", 
"C2", "C3"), class = "data.frame", row.names = c(NA, -12L)) 

각 행은 3 개 개의 숫자의 조합을 갖는다. 저는 모든 트라이 어드를 쌍으로 재결합하려고합니다. 각각의 트라이어드 행은 3 개의 행으로 나뉘어져 있습니다 (각각은 가능한 쌍을 포함하고 있습니다). 예를 들어 행 1 (2, 3, 8)은 행 1 (2, 3), 행 2 (3, 8) 및 행 3 (2, 8)로 변환되어야합니다. (모든 행이 재결합 할 때까지 테이블 반복) 내가 combn 기능이 작업을 수행하려고했습니다

result <- structure(list(Col1 = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L), .Label = c("Row 1", "Row 2", "Row 3"), class = "factor"), 
    Col2 = c(2L, 3L, 2L, 9L, 6L, 9L, 3L, 5L, 3L), Col3 = c(3L, 
    8L, 8L, 6L, 2L, 2L, 5L, 6L, 6L)), .Names = c("Col1", "Col2", 
"Col3"), class = "data.frame", row.names = c(NA, -9L)) 

을 : 결과는 다음과 같아야합니다 t(combn(unlist(t(sequence)),2))하지만이 행렬의 모든 요소 사이에 재결합한다 각 행의 요소 만 재결합하는 것이 아닙니다. 어떤 빛 이니?

답변

1

훨씬 깨끗한 방법이있을 것이라고 확신하지만 관심있는 쌍을 세 번 얻으려면 cbind를 사용하고 rbind를 사용하면됩니다.

sequence <- structure(list(C1 = c(2L, 9L, 3L, 9L, 1L, 8L, 9L, 6L, 4L, 5L, 
3L, 2L), C2 = c(3L, 6L, 5L, 8L, 8L, 7L, 3L, 7L, 2L, 1L, 4L, 1L 
), C3 = c(8L, 2L, 6L, 4L, 6L, 5L, 7L, 4L, 5L, 9L, 1L, 7L)), .Names = c("C1", 
"C2", "C3"), class = "data.frame", row.names = c(NA, -12L)) 

# Essentially what you wanted 
temp.result <- with(sequence, rbind(cbind(C1, C2), cbind(C2, C3), cbind(C1, C3))) 
# Identify which rows we're talking about 
id <- rep(seq(nrow(sequence)), 3) 
# Put it all together 
result <- cbind(id, temp.result) 
# Order it the way you imply in your question 
result <- result[order(result[,1]),] 
# Give it the colnames you want 
colnames(result) <- c("Col1", "Col2", "Col3") 
head(result) 
#  Col1 Col2 Col3 
#[1,] 1 2 3 
#[2,] 1 3 8 
#[3,] 1 2 8 
#[4,] 2 9 6 
#[5,] 2 6 2 
#[6,] 2 9 2 
+0

잘 작동합니다. 고맙습니다! – Werner