jesusgarciab
jesusgarciab

Reputation: 129

Use data frame column names and values to name rows

I have a data frame of different combinations that represent whether a marker is present 1 or not 0

combinations_df <- expand.grid(
marker_a = c(0, 1), 
marker_b = c(0, 1), 
marker_c = c(0, 1), 
marker_d = c(0, 1)
)

   marker_a marker_b marker_c marker_d
1         0        0        0        0
2         1        0        0        0
3         0        1        0        0
4         1        1        0        0
5         0        0        1        0
6         1        0        1        0
7         0        1        1        0
8         1        1        1        0
9         0        0        0        1
10        1        0        0        1
11        0        1        0        1
12        1        1        0        1
13        0        0        1        1
14        1        0        1        1
15        0        1        1        1
16        1        1        1        1

I'm trying to create a vector to assign row names using each column, along with its value.

Example output:

                                                    marker_a marker_b marker_c marker_d
marker_a_0-marker_b_0-marker_c_0-marker_d_0         0        0        0        0
marker_a_1-marker_b_0-marker_c_0-marker_d_0         1        0        0        0
...

Upvotes: 0

Views: 207

Answers (1)

Zach
Zach

Reputation: 1153

This should do it:

apply(combinations_df,
      MARGIN = 1,
      FUN = function(x) {
                            paste0(c(rbind(colnames(combinations_df), x)),
                                   collapse = "-")
                        }
      )

Upvotes: 2

Related Questions