我有一个具有以下结构的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()但仅使用 1 个变量,我的意思是,得到这个结果:
x1 x2
x1 x3
x1 x4
x1 x5
x1 x6
而不是:(有太多我不需要的变量,我想选择 x[i])
x1 x2
...
x2 x1
x2 x2
...
x6 x5
谢谢
我有一个具有以下结构的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()但仅使用 1 个变量,我的意思是,得到这个结果:
x1 x2
x1 x3
x1 x4
x1 x5
x1 x6
而不是:(有太多我不需要的变量,我想选择 x[i])
x1 x2
...
x2 x1
x2 x2
...
x6 x5
谢谢
使用这些数据
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"