Combine Vetors to a Dataframe in R

How can you combine vectors into a dataframe in R. To do that, we can use the function of data.frame() to convert vetors into a dataframe in R. The following is the example.

Step 1: Generating Vetors

# Creat 3 vetors
x_1 = rep(c('City1','City2'),each=5)
print(x_1)
x_2 = rep(c('store1','store2'), 5)
print(x_2)
sales=c(10,20,20,50,30,10,5,4,12,4)
print(sales)

Output:

[1] "City1" "City1" "City1" "City1" "City1" "City2" "City2" "City2" "City2" "City2"
[1] "store1" "store2" "store1" "store2" "store1" "store2" "store1" "store2" "store1" "store2"
[1] 10 20 20 50 30 10 5 4 12 4

Step 2: Combine vetors into a dataframe

# create a dataframe by combining all 3 vetors
df <- data.frame (cities  = x_1,
                  stores = x_2,
                  sales=sales)
print(df)

Output:

 cities stores sales
1 City1 store1 10
2 City1 store2 20
3 City1 store1 20
4 City1 store2 50
5 City1 store1 30
6 City2 store2 10
7 City2 store1 5
8 City2 store2 4
9 City2 store1 12
10 City2 store2 4

Further Reading