Assigning value to a new variable from existing column using for loop
<p>I am trying to create a new time series variable where the data consists of 4 static variables and time series data across columns.
I need to get the values from each time series column against each year</p>

<pre><code>A B    C    year  Del_0 Del_1 Del_2 Del_3 Del_4.....
1 abc  qwe  2012  1     2      3    4     5
1 abc  qwe  2013  3     5      3    6     8
1 def  qwe  2014  2     3      6    2     1
1 def  qwe  2013  12    23     21   45    43
</code></pre>

<p>I need to get the first value which is Del_0 for the latest year, Del_1 value against previous year and so on within each group of A,B and C.</p>

<p>I did an aggregate to get the max year for each class </p>

<pre><code>  max_year&lt;-     aggregate(newdata$Year,by=list(newdata$A,newdata$B,newdata$C),max)
</code></pre>

<p>I merged it back to original data</p>

<pre><code>newdata1&lt;-merge(x=newdata,y=max_year,by=c("A","B","C"),all=TRUE)

newdata1$diff=newdata1$max_yr-newdata1$Year#Calculating difference
</code></pre>

<p>I am trying to get the Del_0 value for the latest year using the difference value which would be 0 for the latest year within each group.</p>

<p>I am trying to use for loop.</p>

<pre><code>for(i in 0:4){
df[[paste(i, 'AVG', sep="_")]]&lt;-newdata1$Del[i]
}

final data would be
A B    C    year  Del_0 Del_1 Del_2 Del_3 Del_4.....Avg0 Avg1 Avg2 Avg3 Avg4
1 abc  qwe  2012  1     2      3    4     5                2
1 abc  qwe  2013  3     5      3    6     8         3
1 def  qwe  2013  12    23     21   45    43               23
1 def  qwe  2014  2     3      6    2     1         2 
</code></pre>