Rob
Rob

Reputation: 1490

Reduce all columns of data.frame to one long vector

Probably quite a basic question, but can't seem to figure this out by myself.

I have a data.frame like this:

 df <- data.frame(X1=1:4,X2=5:8,X3=9:12)

I would like to create one long vector from all columns, that, for the example, would look as following:

 [1]  1  2  3  4  5  6  7  8  9 10 11 12

How do I do this?

Thanks!

Upvotes: 0

Views: 651

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61164

Another alternative:

> stack(df)[,1]
 [1]  1  2  3  4  5  6  7  8  9 10 11 12

Upvotes: 2

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

A data.frame is a special type of list, so to get what you want, you can just use:

unlist(df, use.names = FALSE)
# [1]  1  2  3  4  5  6  7  8  9 10 11 12

Upvotes: 4

Related Questions