Transpose multiple rows with one single column

2.2k views Asked by At

I have the following data frame:

a<-c(2,1,3,6,7)
b<-c(3,1,4,5,8)
c<-c(9,2,5,4,7)



d<- data.frame(a,b,c)
      a b c
    1 2 3 9
    2 1 1 2
    3 3 4 5
    4 6 5 4
    5 7 8 7

And I would like to transpose the five rows with one single column, like this:

2
3
9
1
1
2
3
4
5
6
5
4
7
8
7
2

There are 2 answers

1
zx8754 On BEST ANSWER

Try this:

matrix(t(d),ncol=1)

Transpose data.frame and redefine as matrix with 1 column.

Thanks to @DavidArenburg, we can also do:

c(t(d))
2
Kartik Kumar On

Lets assume there is a 2-D array that needs to be operated upon in the manner you mentioned. Lets call the array sample[rows][cols], where rows and cols are the sizes of well, rows and columns. I shall give a sample code of the function in C++ that will return the final column vector, as in, it will be an array which you basically can use as the column vector that you required.

    int ret_col(int sample[][])
    {
           int i,j,k=0;
           int final_column[rows*cols];

           for(i=0;i<cols;i++)
           {
               for(j=0;j<rows;j++)
               {
                   final_column[k++]=a[j][i];
               }
           }

           return final_column;
    }

If there is anything that was not clear in my code, please feel free to ask. Hope this helped! :)