1

I have a dataframe as below. I want to take ww1 column and create a new column newww1 as follows:

My Excel formula is

=2012&TEXT((LEFT(201438,4)-2012)*53+RIGHT(201438,2),"0000")

where instead of 201438 I will have a value from column ww1

the explanation of my formula is:

take left 4 characters of ww1
subtract 2012 from them
multiply answer by 53
add answer to right 2 characters of ww1
print answer in "0000" format
concatenate that answer with 2012.

My data

PRODUCT=c(rep("A",4),rep("B",2))
ww1=c(201438,201440,201444,201446,201411,201412)
ww2=ww1-6
DIFF=rep(6,6)
DEMAND=rep(100,6)

df=data.frame(PRODUCT,ww1,ww2,DIFF,DEMAND)

df

  PRODUCT    ww1    ww2 DIFF DEMAND
1       A 201438 201432    6    100
2       A 201440 201434    6    100
3       A 201444 201438    6    100
4       A 201446 201440    6    100
5       B 201411 201405    6    100
6       B 201412 201406    6    100

This is how my data will look at the end

    PRODUCT ww1 ww2 DIFF    DEMAND  newww1
1   A   201438  201432  6   100 20120144
2   A   201440  201434  6   100 20120146
3   A   201444  201438  6   100 20120150
4   A   201446  201440  6   100 20120152
5   B   201411  201405  6   100 20120117
6   B   201412  201406  6   100 20120118
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2543622
  • 5,760
  • 25
  • 91
  • 159
  • The answer below is exactly what you're looking for, but there are a few more options available here: http://stackoverflow.com/questions/15498235/how-to-split-a-number-into-digits-in-r –  May 31 '15 at 02:53

1 Answers1

1
df$newww1 = paste0('2012', sprintf('%04d', 
                    53 * (as.numeric(substr(df$ww1, 1, 4)) - 2012) + 
                          as.numeric(substr(df$ww1, 5, 6))
                         )
                  )
user2034412
  • 4,102
  • 2
  • 23
  • 22