Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a dataframe to a vector (by rows)

I have a dataframe with numeric entries like this one

test <- data.frame(x = c(26, 21, 20), y = c(34, 29, 28)) 

How can I get the following vector?

> 26, 34, 21, 29, 20, 28 

I was able to get it using the following, but I guess there should be a much more elegant way

X <- test[1, ] for (i in 2:dim(test)[ 1 ]){    X <- cbind(X, test[i, ])    }  
like image 984
Brani Avatar asked Mar 30 '10 12:03

Brani


People also ask

How do I turn a Dataframe row into a vector?

If we want to turn a dataframe row into a character vector then we can use as. character() method In R, we can construct a character vector by enclosing the vector values in double quotation marks, but if we want to create a character vector from data frame row values, we can use the as character function.

How do you vectorize a data frame?

To create a vector of data frame values by rows we can use c function after transposing the data frame with t. For example, if we have a data frame df that contains many columns then the df values can be transformed into a vector by using c(t(df)), this will print the values of the data frame row by row.

How do I convert a row vector to a column vector 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. The result of the t() command is always a matrix object.


2 Answers

You can try as.vector(t(test)). Please note that, if you want to do it by columns you should use unlist(test).

like image 183
teucer Avatar answered Oct 07 '22 15:10

teucer


c(df$x, df$y) # returns: 26 21 20 34 29 28 

if the particular order is important then:

M = as.matrix(df) c(m[1,], c[2,], c[3,]) # returns 26 34 21 29 20 28  

Or more generally:

m = as.matrix(df) q = c() for (i in seq(1:nrow(m))){   q = c(q, m[i,]) }  # returns 26 34 21 29 20 28 
like image 38
doug Avatar answered Oct 07 '22 14:10

doug