Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rbind two vectors in R

Tags:

r

vector

rbind

I have a data.frame with several columns I'd like to join into one column in a new data.frame.

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

how would I create a new data.frame with a single column that's 1:9?

like image 873
screechOwl Avatar asked Jul 05 '15 16:07

screechOwl


People also ask

How do I Rbind two data frames in R?

To join two data frames (datasets) vertically, use the rbind function. The two data frames must have the same variables, but they do not have to be in the same order. If data frameA has variables that data frameB does not, then either: Delete the extra variables in data frameA or.

What does Rbind () do in R?

rbind() in R The rbind() function can be used to bind or combine several vectors, matrices, or data frames by rows.

How do I add two vectors in R?

To concatenate two or more vectors in r we can use the combination function in R. Let's assume we have 3 vectors vec1, vec2, vec3 the concatenation of these vectors can be done as c(vec1, vec2, vec3). Also, we can concatenate different types of vectors at the same time using the same function.

What is the use of Rbind () and Cbind () in R?

cbind() and rbind() both create matrices by combining several vectors of the same length. cbind() combines vectors as columns, while rbind() combines them as rows.


2 Answers

Since data.frames are essentially lists of columns, unlist(df1) will give you one large vector of all the values. Now you can simply construct a new data.frame from it:

data.frame(col = unlist(df1))
like image 160
Konrad Rudolph Avatar answered Sep 24 '22 16:09

Konrad Rudolph


In case you want an indicator too:

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
like image 25
Neal Fultz Avatar answered Sep 23 '22 16:09

Neal Fultz