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?
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.
rbind() in R The rbind() function can be used to bind or combine several vectors, matrices, or data frames by rows.
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.
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.
Since data.frame
s 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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With