考虑以下矩阵:
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))
但这会重新组合矩阵中的所有元素,而不是仅重新组合每行的元素。有光吗?
答案 0 :(得分: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