85

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, ])
   } 
zx8754
  • 52,746
  • 12
  • 114
  • 209
Brani
  • 6,454
  • 15
  • 46
  • 49

3 Answers3

164

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

eddi
  • 49,088
  • 6
  • 104
  • 155
teucer
  • 6,060
  • 2
  • 26
  • 36
  • 1
    I can not understand of this workaround. could give some more explanations? @teucer – verystrongjoe Aug 30 '16 at 10:21
  • 6
    @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 – teucer Aug 31 '16 at 02:25
  • 3
    I had to use `as.numeric(t(df))` – citynorman Nov 30 '16 at 15:53
  • 1
    `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)))` –  Apr 15 '20 at 11:09
11
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
doug
  • 69,080
  • 24
  • 165
  • 199
  • 1
    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. – Brani Mar 30 '10 at 13:04
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
Emma
  • 27,428
  • 11
  • 44
  • 69