Rbind two vectors in r

I have a data.frame with several columns that I would like to combine into one column in a new data.frame.

df1 <- data.frame(col1 = 1:3, col2 = 4:6, col3 = 7:9) 

how can i create a new data.frame with one column which is 1: 9?

+8
vector r rbind
source share
6 answers

Since data.frame is a list of columns, unlist(df1) will give you one big vector of all values. Now you can just build a new data.frame from it:

 data.frame(col = unlist(df1)) 
+9
source share

If you also want an indicator:

 stack(df1) # values ind # 1 1 col1 # 2 2 col1 # 3 3 col1 # 4 4 col2 # 5 5 col2 # 6 6 col2 # 7 7 col3 # 8 8 col3 # 9 9 col3 
+6
source share

To provide a complete set of ways to do this, run tidyr .

 library(tidyr) gather(df1) key value 1 col1 1 2 col1 2 3 col1 3 4 col2 4 5 col2 5 6 col2 6 7 col3 7 8 col3 8 9 col3 9 
+6
source share

Another c function:

 data.frame(col11 = c(df1,recursive=TRUE)) col11 col11 1 col12 2 col13 3 col21 4 col22 5 col23 6 col31 7 col32 8 col33 9 
+6
source share

You can try:

 as.data.frame(as.vector(as.matrix(df1))) # as.vector(as.matrix(df1)) #1 1 #2 2 #3 3 #4 4 #5 5 #6 6 #7 7 #8 8 #9 9 
+5
source share

Another approach, just to use Reduce ...

 data.frame(Reduce(c, df1)) 
+2
source share

All Articles