penguin
penguin

Reputation: 1376

How to append multiple columns of a dataframe?

I am trying to combine multiple columns of a dataframe in R into a single vector. What is the easiest way to do this?

My dataframe looks like:

X1    X2    X3     X4
----------------------
Paul  John  Cissy  Paul
Rob   Rob   Rob    Amanda

And the desired output is

X1
---
Paul
Rob
John
Rob
Cissy
Rob
Paul
Amanda

Upvotes: 3

Views: 2247

Answers (3)

akrun
akrun

Reputation: 887851

We can try

data.frame(X1 = c(as.matrix(df)))
#      X1
#1   Paul
#2    Rob
#3   John
#4    Rob
#5  Cissy
#6    Rob
#7   Paul
#8 Amanda

Upvotes: 2

Sotos
Sotos

Reputation: 51592

One idea using stack

df5[] <- lapply(df5[], as.character) #make sure your columns are not factors
setNames(stack(df5)[1], 'X1')

#      X1
#1   Paul
#2    Rob
#3   John
#4    Rob
#5  Cissy
#6    Rob
#7   Paul
#8 Amanda

Upvotes: 3

Wietze314
Wietze314

Reputation: 6020

use unlist:

df <- data.frame(X1 = c("Paul","Rob"), X2 = c("John", "Rob"))
v <- unlist(df)

gives:

> str(v)

Factor w/ 3 levels "Paul","Rob","John": 1 2 3 2
- attr(*, "names")= chr [1:4] "X11" "X12" "X21" "X22"

you can use unname(v) to remove the attribute names.

Upvotes: 3

Related Questions