我有一个格式如下的数据框:
localEng = create_engine('postgresql+psycopg2://[user]:[pass]@[host]:[port]/[schema]', echo=False)
我想让每两个列的组合在彼此之下,如
A B C D
----------
x1 x2 x3 x4
y1 y2 y3 y4
答案 0 :(得分:0)
我们可以使用combn
do.call(rbind, combn(seq_along(df), 2, FUN =
function(x) cbind(df[,x[1]], df[,x[2]]), simplify = FALSE))
# [,1] [,2]
# [1,] "x1" "x2"
# [2,] "y1" "y2"
# [3,] "x1" "x3"
# [4,] "y1" "y3"
# [5,] "x1" "x4"
# [6,] "y1" "y4"
# [7,] "x2" "x3"
# [8,] "y2" "y3"
# [9,] "x2" "x4"
#[10,] "y2" "y4"
#[11,] "x3" "x4"
#[12,] "y3" "y4"
或更紧凑
data.table::rbindlist(combn(df, 2, simplify = FALSE))
df <- structure(list(A = c("x1", "y1"), B = c("x2", "y2"), C = c("x3",
"y3"), D = c("x4", "y4")), .Names = c("A", "B", "C", "D"),
class = "data.frame", row.names = c("1", "2"))