仅将数据帧R合并为1个变量

时间:2015-12-17 20:15:38

标签: r combinations combn

我有一个data.frame,结构如下:

x1 x2 x3 x4 x5 x6
 y  n  y  n  n  y
 n  n  y  n  n  y
 y  y  y  y  y  n

我想组合 combn(),但仅使用变量中的一个,我的意思是,得到这个结果:

x1 x2
x1 x3
x1 x4
x1 x5
x1 x6

而不是:(有太多的varibales,我不需要,我想选择x [i])

x1 x2
...
x2 x1
x2 x2
...
x6 x5

谢谢

1 个答案:

答案 0 :(得分:1)

使用此数据

your_data = structure(list(x1 = structure(c(2L, 1L, 2L), .Label = c("n", 
"y"), class = "factor"), x2 = structure(c(1L, 1L, 2L), .Label = c("n", 
"y"), class = "factor"), x3 = structure(c(1L, 1L, 1L), .Label = "y", class = "factor"), 
    x4 = structure(c(1L, 1L, 2L), .Label = c("n", "y"), class = "factor"), 
    x5 = structure(c(1L, 1L, 2L), .Label = c("n", "y"), class = "factor"), 
    x6 = structure(c(2L, 2L, 1L), .Label = c("n", "y"), class = "factor")), .Names = c("x1", 
"x2", "x3", "x4", "x5", "x6"), class = "data.frame", row.names = c(NA, 
-3L))

这符合您要求的输出:

cbind(names(your_data)[1], names(your_data)[-1])
#      [,1] [,2]
# [1,] "x1" "x2"
# [2,] "x1" "x3"
# [3,] "x1" "x4"
# [4,] "x1" "x5"
# [5,] "x1" "x6"

它是一个矩阵,但您可以使用as.data.frame轻松转换为数据框。您也可以根据您想要的第一个位置的列号对其进行功能化。

single_combn = function(vec, pos) {
    cbind(vec[pos], vec[-pos])
}

使用示例:

single_combn(names(your_data), 1)
#      [,1] [,2]
# [1,] "x1" "x2"
# [2,] "x1" "x3"
# [3,] "x1" "x4"
# [4,] "x1" "x5"
# [5,] "x1" "x6"

single_combn(names(your_data), 3)
#      [,1] [,2]
# [1,] "x3" "x1"
# [2,] "x3" "x2"
# [3,] "x3" "x4"
# [4,] "x3" "x5"
# [5,] "x3" "x6"