anthe.sevenants

How to create a data frame from multiple vectors in R

2023-02-21

Imagine you have three different vectors or lists in R:

index = 1:5
location = c("New York", "Rio", "Tokio", "Brussels", "Ushuaia")
boing_index = c(12, 19, 0, 77, 2)

You want these three vectors to be the columns of a new data frame. This means that the first elements of each column contitute the first row, the second elements the second row, and so on.

To achieve this, just call the data.frame() function. You can pass multiple named arguments to this function. These names of the arguments will be the column names of your new data frame. Then, the arguments themselves will be the values for these columns:

df <- data.frame(index = index,
                 location = location,
                 boing_index = boing_index)

The result is the data frame we set out to build:

The resulting data frame