[r] 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?

This question is related to r dataframe

The answer is


This should do the trick, to produce the data frame you asked for, using only base R:

df <- data.frame(cond=c(rep("x", times=length(x)), 
                        rep("y", times=length(y))), 
                 rating=c(x, y))

df
  cond rating
1    x      1
2    x      2
3    x      3
4    y    100
5    y    200
6    y    300

However, from your initial description, I'd say that this is perhaps a more likely usecase:

df2 <- data.frame(x, y)
colnames(df2) <- c(x_name, y_name)

df2
  cond rating
1    1    100
2    2    200
3    3    300

[edit: moved parentheses in example 1]


While this does not answer the question asked, it answers a related question that many people have had:

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

df <- data.frame(x,y)
names(df) <- c(x_name,y_name)
print(df)

  cond rating
1    1    100
2    2    200
3    3    300

You can use expand.grid( ) function.

x <-c(1,2,3)
y <-c(100,200,300)
expand.grid(cond=x,rating=y)

Alt simplification of https://stackoverflow.com/users/1969435/gx1sptdtda above:

cond <-c(1,2,3)
rating <-c(100,200,300)
df <- data.frame(cond, rating)
df
  cond rating
1    1    100
2    2    200
3    3    300

df = data.frame(cond=c(rep("x",3),rep("y",3)),rating=c(x,y))


Here's a simple function. It generates a data frame and automatically uses the names of the vectors as values for the first column.

myfunc <- function(a, b, names = NULL) {
  setNames(data.frame(c(rep(deparse(substitute(a)), length(a)), 
                        rep(deparse(substitute(b)), length(b))), c(a, b)), names)
}

An example:

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

myfunc(x, y, c(x_name, y_name))

  cond rating
1    x      1
2    x      2
3    x      3
4    y    100
5    y    200
6    y    300