neversaint neversaint - 2 months ago 29
R Question

How to combine two vectors into a data frame

I have two vectors like this

x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"


I'd like to output the dataframe like this:

> print(df)
cond rating
1 x 1
2 x 2
3 x 3
4 y 100
5 y 200
6 y 300


What's the way to do it?

Answer
x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"

require(reshape2)
df <- melt(data.frame(x,y))
colnames(df) <- c(x_name, y_name)
print(df)
Comments