Convert a dataframe to a vector (by rows)

192,469

Solution 1

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

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

You can try this to get your combination:

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

which will return:

26, 34, 21, 29, 20, 28
Share:
192,469

Related videos on Youtube

Brani
Author by

Brani

Updated on July 31, 2020

Comments

  • Brani
    Brani almost 4 years

    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, ])
       } 
    
  • Brani
    Brani about 14 years
    Yes, order does matter, I want convertion by rows. And the rows are many more than 3. So it would be better if you could transform this to a loop or use a vectorized function. Thank you.
  • verystrongjoe
    verystrongjoe over 7 years
    I can not understand of this workaround. could give some more explanations? @teucer
  • teucer
    teucer over 7 years
    @verystrongjoe there are two things going on here: 1) t implicitly converts a data.frame to a matrix, 2) a matrix is just a special vector with dim attribute and as.vector or c removes it
  • citynorman
    citynorman over 7 years
    I had to use as.numeric(t(df))
  • Admin
    Admin about 4 years
    unlist does not work if columns have different class. See unlist(data.frame(a= 1:10, b= letters[1:10])), for example. I ended up using do.call("c", lapply(data.frame(a= 1:10, b= letters[1:10]), function(i) as.character(i)))