I want to calculate the weekly price change in a list of products that I have, but I am having issues even pulling in the values. df1 is a list of products and the dates I am interested in, df2 is the price history of all products. I want to add a new column to df1 with the % price change for 1 week (1 week from date in df1)
df1:
Item Date 1W Px Change
A 1/1/17
B 2/1/17
A 2/2/17
C 2/2/17
D 3/1/17
df2:
Date A B C D
1/1/17 1 5 10 50
1/2/17 2 5 9 40
1/3/17 3 5 10 42
The dataframes have thousands of products and dates. I tried with a for loop to create a new vector with just the price from the day in df1 but getting a replacement has length zero error.
price <- rep(NA,nrow(df1))
for(i in 1:nrow(df1)){
price[i] <- df2[which(df2$Date==df1$Date[i]),df1$Item[i]]
}
Any ideas on how to either fix the for loop, or if there is a better way for me to do this? Thanks