1

I have a dataframe which look something like this

co_code   company_name   year   week   returns
1          A             2008    40     0.45
1          A             2008    41     0.33
1          A             2008    42     0.31
.
.
.
2          B             2002    01     0.22
2          B             2002    02     0.32
.
.
.

And so on. Years and week differs from company to company.

I want a separate column which replaces year and week into date. Here date should be last day of the week

Output should look something like this

co_code   company_name   date        returns
1          A             2008-10-11    0.45
1          A             2008-10-18    0.33
1          A             2008-10-25    0.31
.
.
.
2          B             2002-01-07    0.22
2          B             2002-01-14    0.32

Note:- This change should not affect ordering of dataframe. Rows should not get disturbed

1 Answers1

2

You can use this-

library(data.table)
setDT(dt)[,date:=as.Date(paste(year, week, 6, sep="-"), "%Y-%U-%u")]

Output-

co_code company_name year week returns       date
1:       1            A 2008   40    0.45 2008-10-11
2:       1            A 2008   41    0.33 2008-10-18
3:       1            A 2008   42    0.31 2008-10-25

Input data-

dt <- read.table(text="co_code   company_name   year   week   returns
1          A             2008    40     0.45
1          A             2008    41     0.33
1          A             2008    42     0.31",header=T)

Note- I have used 6th day of a week to match desired output. But, we can change that to whatever we required.

Rushabh Patel
  • 2,672
  • 13
  • 34