0

I want to expand a df with time column.

Here I have 2 df:

book1 <- data.frame(
  id = c('A1', 'A2', 'A3')
)
book2 <- data.frame(
  year = c('2000', '2010', '2020')  
)

> book1
  id
1 A1
2 A2
3 A3

> book2
  year
1 2000
2 2010
3 2020

What I expect is

  id year
1 A1 2000
2 A1 2010
3 A1 2020
4 A2 2000
5 A2 2010
6 A2 2020
7 A3 2000
8 A3 2010
9 A3 2020

Could anyone help me to do this? Thank you!

J.D
  • 1,885
  • 4
  • 11
  • 19

2 Answers2

1

Use expand.grid:

df <- expand.grid(book1$id, book2$year)
df
Henry Cyranka
  • 2,970
  • 1
  • 16
  • 21
1

You can use merge(). For desired ordering of the result, we use book2 as the first argument and then reverse the column order of the result.

rev(merge(book2, book1))
#   id year
# 1 A1 2000
# 2 A1 2010
# 3 A1 2020
# 4 A2 2000
# 5 A2 2010
# 6 A2 2020
# 7 A3 2000
# 8 A3 2010
# 9 A3 2020
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245