Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting rows as a single column in r

Tags:

r

reshape

I have the following data.frame x

a d g
b e h
c f i

Note: letters are used as an example. The actual data.frame has numbers in place of letters (real data which are not in ascending order, as in this example)

I want to transform it in an unique column, by putting columns from 2 to 4 under the first. The expected result is the following

a
b
c
d
e
f
g
h
i

I tried the following code

matrix(t(x), ncol=1, nrow=ncol(x)*nrow(x), byrow=F)

but it gives (obviously) the following

a
d 
g
b
e
h
c
f
i
like image 464
Bob Avatar asked Sep 18 '13 13:09

Bob


People also ask

How do I make a row into a column in R?

Rotating or transposing R objects frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command.

How do I convert rows to single columns?

Here is how it looks: Select and copy the needed range. Right-click on a cell where you want to convert rows to columns. Select the Paste Transpose option to rotate rows to columns.

How do I convert multiple columns to a single column in R?

Convert multiple columns into a single column, To combine numerous data frame columns into one column, use the union() function from the tidyr package.

How do I transpose rows to columns in R?

To interchange rows with columns, you can use the t() function. For example, if you have the matrix (or dataframe) mat you can transpose it by typing t(mat) . This will, as previously hinted, result in a new matrix that is obtained by exchanging the rows and columns.


2 Answers

Something like this?

X <- matrix(letters[1:9], ncol=3)
matrix(X, ncol=1)

R matrices are in column major order, so you can easily concatenate them into a single column vector with the matrix function.

like image 147
Jason Morgan Avatar answered Oct 19 '22 16:10

Jason Morgan


I find stack also very useful

X <- data.frame(matrix(letters[1:9], ncol=3),stringsAsFactors=FALSE)
stack(X)[,"values",drop=FALSE]
like image 45
cryo111 Avatar answered Oct 19 '22 15:10

cryo111