Search code examples
rheader

Columns of 1 data table become additional headers on another data.frame


One data table is generated via:

q <- data.frame(ID = c(1:5), replicate(10,sample(50:100,5,rep=TRUE))))

and another:

y <- data.frame(ID = c(1:10), replicate(2,sample(1:5,10,rep=TRUE))))

Renaming columns names in y,

colnames(y) <- c("size", "category")

Am trying to add two more header lines to q, using the columns in y - the heading "category" (with integers) would be the (new) second line, with heading "size" (with integers) the third new line.

My output should look something like this per screenshot (first 5 lines only)-

enter image description here

The output shows an ID column (x-axis), and X1, X2, X3.... (y1, y2, y3... values). Between ID and X1 can be seen the 2 new headers, Category and Size. I think this will require a new column, so as not to encroach on the ID column.

Thx


Solution

  • If I understood correctly, here you go:

    q <- rbind(c(colnames(y[2]),y[,2]),c(colnames(y[1]),y[,1]), q)
    

    After edits:

    # same as above plus some new column
    q <- rbind(c(NA,colnames(y[2]),y[,2]),c(NA,colnames(y[1]),y[,1]), cbind(q[,1], NA, q[,2:11]))
    
    # add column names
    colnames(q)[1:2] <- c("ID","new_col")