How to combine two vectors into a data frame
dataframe, r
Solution
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)
UPDATE (2017-02-07): As an answer to @cdaringe comment - there are multiple solutions possible, one of them is below.
library(dplyr)
library(magrittr)
x <- c(1, 2, 3)
y <- c(100, 200, 300)
z <- c(1, 2, 3, 4, 5)
x_name <- "cond"
y_name <- "rating"
# Helper function to create data.frame for the chunk of the data
prepare <- function(name, value, xname = x_name, yname = y_name) {
data_frame(rep(name, length(value)), value) %>%
set_colnames(c(xname, yname))
}
bind_rows(
prepare("x", x),
prepare("y", y),
prepare("z", z)
)
Problem
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?