Ochetski
Ochetski

Reputation: 115

combn dataframe R for 1 variable only

I have a data.frame with the following structure:

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

I want to make combinations combn() but using only for only 1 of the variable, I mean, gettingthis result:

x1 x2
x1 x3
x1 x4
x1 x5
x1 x6

Instead of: (there are too many varibales that I dont need, and I want to choose the x[i])

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

Thank you

Upvotes: 0

Views: 163

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145755

Using this data

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

This matches the output you ask for:

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"

It's a matrix, but you could easily convert to data frame with as.data.frame. You could also functionalize it based on the column number you want in the first position.

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

Use example:

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"

Upvotes: 1

Related Questions