Convert a dataframe to a vector (by rows)

RDataframeVectorR Faq

R Problem Overview


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, ])
   } 

R Solutions


Solution 1 - R

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

Solution 2 - R

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

Solution 3 - R

You can try this to get your combination:

as.numeric(rbind(test$x, test$y))

which will return:

26, 34, 21, 29, 20, 28

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBraniView Question on Stackoverflow
Solution 1 - RteucerView Answer on Stackoverflow
Solution 2 - RdougView Answer on Stackoverflow
Solution 3 - RWilinthon Bogoya ForeroView Answer on Stackoverflow