将前一周的数据与当前的R周结合起来

时间:2017-05-24 04:07:31

标签: r

嗨,我有一个下面给出的数据框

s.no week number   Income
1     6            52 
2     7            74 
3     8            13 
4     9            60

我需要更改此数据框,并添加一个新列Total_income,其公式为

 100% value of Income in current week + 
  60% value of income in previous week + 
  30% value of income in previous to previous week

输出应该像 -

s.no week number Income Total_Income
 1      6          52      52
 2      7          74      74+0.6(52)=105.2
 3      8          13      13+0.6(74)+0.3(52) = 73
 4      9          60      60+0.6(13)+0.3(74) = 90

请帮助

3 个答案:

答案 0 :(得分:1)

假设数据框data按周编号排序。如果没有,请从data %>% arrange(week_number) %>%开始(注意列重命名以删除空格)。

library(dplyr)
data %>% 
  mutate(Total_Income = Income + 0.6 * lag(Income, default = 0) + 
         0.3 * lag(Income, n = 2, default = 0))

答案 1 :(得分:1)

带有sapply的基本R选项。对于week_number中的每个值,我们找到该周的Income以及前两周,并将它们与必要的算术相加。

with(df, sapply(week_number, function(x) { sum(Income[week_number == x], 
  0.6 * Income[week_number == x-1], 0.3 *Income[week_number == x-2])
}))

#[1]  52.0 105.2  73.0  90.0

答案 2 :(得分:1)

我们可以使用data.table并在一行中执行此操作

library(data.table)
setDT(d)[,Total_Income := Reduce(`+`, Map(`*`,shift(Income,n=0:2,fill=0), c(1, 0.6, 0.3)))]
d
#   s.no weeknumber Income Total_Income
#1:    1          6     52         52.0
#2:    2          7     74        105.2
#3:    3          8     13         73.0
#4:    4          9     60         90.0

或者我们可以做一个交叉产品

c(crossprod(do.call(rbind, shift(d$Income, n = 0:2, fill = 0)), c(1, 0.6, 0.3)))
#[1]  52.0 105.2  73.0  90.0