本文介绍了R文字操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下数据框。我想采用ww1列并按如下方式创建新列newww1:
I have a dataframe as below. I want to take ww1 column and create a new column newww1 as follows:
我的Excel公式为
=2012&TEXT((LEFT(201438,4)-2012)*53+RIGHT(201438,2),"0000")
其中,我将使用ww1列中的值代替201438
where instead of 201438 I will have a value from column ww1
我的公式的解释是:
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.
我的数据
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
推荐答案
df$newww1 = paste0('2012', sprintf('%04d',
53 * (as.numeric(substr(df$ww1, 1, 4)) - 2012) +
as.numeric(substr(df$ww1, 5, 6))
)
)
这篇关于R文字操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!