tomathon
tomathon

Reputation: 854

Combining two columns into one R

Just a quick question that I am struggling with. I am working in R and have a data frame like so:

>df
V1      V2
Todd    SAFEZONE
Mike    COOLDOWN
Larry   CHICKGUY

And I want to combine the two columns so that I have a resulting data frame with one column where the two factors sharing a column end up one after another:

>df2
V1
Todd
SAFEZONE
Mike
COOLDOWN
Larry
CHICKGUY

What is the most efficient way to do this? Sorry if too simple, there are some tricks to text manipulation I need to learn.

Thanks in advance.

Upvotes: 1

Views: 5360

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

The resulting column name is easy to change

> df2 <- do.call(rbind, lapply(1:nrow(df), function(x) t(df[x,])))
> rownames(df2) <- NULL
> df2
##      1         
## [1,] "Todd"    
## [2,] "SAFEZONE"
## [3,] "Mike"    
## [4,] "COOLDOWN"
## [5,] "Larry"   
## [6,] "CHICKGUY"

Upvotes: 2

David Marx
David Marx

Reputation: 8558

Append (or extract) the two columns so they are side by side, and then flatten the matrix into a single vector. The flattening goes by row, so this will produce a vector whose elements alternate from each column. Here's a demo:

x1=c('a','b','c')
x2=c('x','y','z')
matrix(rbind(x1,x2),ncol=1)

    [,1]
[1,] "a" 
[2,] "x" 
[3,] "b" 
[4,] "y" 
[5,] "c" 
[6,] "z" 

Upvotes: 4

Related Questions