I am trying to paste a unique value from one dataframe into a newly created column in a separate dataframe. The function requires multiple conditions to be met. In this case both the 'Date' and 'Product' values must be identical in both dataframes.
I have tried for, if and while functions but I cannot seem to crack the problem.
sales1 <- data.frame("Day" = c(01,02,03,04), "Product" = c("B","A","D","C"), "salesVol" = c(12,31,3,90))
sales2 <- data.frame("Day" = c(01,01,01,01,02,02,02,02,03,03,03,03,04,04,04,04), "Product" = c("A","B","C","D","A","B","C","D","A","B","C","D","A","B","C","D"), "Price" = c(9,3,4,5,7,10,5,8,4,5,11,3,12,4,7,6))
for (i in 1:nrow(sales1)){
if (sales1$Product == sales2$Product
&& sales1$Day == sales2$Day)
{
sales1$dailyPrice[i] <- sales2$Price[i]
}
}
Note that there can only be one unique combination of date/product within sales2.
Also tried:
while (sales1$Product == sales2$Product
&& sales1$Day == sales2$Day){
sales1$dailyPrice <- sales2$Price
}
The resulting sales1 dataframe should be:
Day Product salesVol dailyPrice
1 B 12 3
2 A 31 7
3 D 3 3
4 C 90 7
i.e. when the day is 2 and the the product is 'A', the 'dailyPrice' is 7 as per sales2.
However at best I get incorrect values and at worst (above code) nothing gets pasted. No error messages either. Thanks.
Aucun commentaire:
Enregistrer un commentaire