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 个数字的组合。我正在尝试将所有三元组重新组合成对,每个三元组行分为三行(每行包含一个可能的对)。例如,第 1 行 (2, 3, 8) 应转换为第 1 行 (2, 3)、第 2 行 (3, 8) 和第 3 行 (2, 8)。结果应如下所示:

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))

(表格重复,直到所有行都重新组合)

我尝试使用 combn 函数来做到这一点:t(combn(unlist(t(sequence)),2))但这是重新组合矩阵的所有元素,而不是仅重新组合每一行的元素。有光吗?

4

1 回答 1

1

我敢肯定有一种更清洁的方法,但您可以使用 cbind 获得兴趣对 3 次,然后使用 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
于 2012-05-28T21:09:25.333 回答