0

How can I create a dataframe with column A * column B.

For example, column 'year' (2018 - 2025) and for each year a column 'week' from 1:52.

Basically, I want a nicer way to get this result:

a =data.table( c(2018) , c(1:52)) 
x <- c("year", "week")
colnames(a) <- x


b =data.table(c(2019) , c(1:52)) 
x <- c("year", "week")
colnames(b) <- x

c =data.table(c(2020) , c(1:52)) 
x <- c("year", "week")
colnames(c) <- x

d = rbind(a, b, c)

EDIT: Thanks!!

6 Answers6

2
d <- expand.grid(year = c(2018:2020), week = c(1:52))
Kerry Jackson
  • 1,821
  • 12
  • 20
2

Use crossing from the tidyr package. something like:

library(tidyr)
library(data.table)
crossing(
  data.table(year=2018:2020),
  data.table(week=1:52))

for more details, see https://stackoverflow.com/a/49630818/1358308

Sam Mason
  • 15,216
  • 1
  • 41
  • 60
  • 1
    the question felt like a duplicate so didn't feel it was worth putting much effort in… have added an example now – Sam Mason Sep 07 '18 at 13:53
1

With base R

data.frame(year = rep(2018:2020, 52), week = rep(1:52, length(year)))
nghauran
  • 6,648
  • 2
  • 20
  • 29
1

Since you seem to use data.table, here is one more option.

library(data.table)
CJ('year' = 2018:2020, 'week' = 1:52)
#     year week
#  1: 2018    1
#  2: 2018    2
#  3: 2018    3
#  4: 2018    4
#  5: 2018    5
# ---        
#152: 2020   48
#153: 2020   49
#154: 2020   50
#155: 2020   51
#156: 2020   52
markus
  • 25,843
  • 5
  • 39
  • 58
0

You just need to call data.frame

data.frame(year=rep(2018:2020,52),weak=rep(c(1:52),3))
Sal-laS
  • 11,016
  • 25
  • 99
  • 169
0

Basically,

year = rep(c(2018:2025),each = 52)
week = rep(c(1:52), length(c(2018:2025)))
d = as.data.frame(cbind(year, week))
Maik
  • 170
  • 7