2014年和2015年的價格。請注意,2015年有一件商品在2014年未與其匹配。首先生成散列作爲關鍵字,然後匹配將該商品的2014年價格導入到2015年的數據框中。後來分化:
df2014 <- data.frame(Date = as.Date(c("2014-09-01", "2014-09-01")),
Shop = c("Asda", "Tesco"),
Item = c("Apple", "Pear"),
ProductKey = c("0f-7c-32-9c65","7c-e9-a0-a11c"),
Price = c(2.00, 1.50), stringsAsFactors = FALSE)
df2015 <- data.frame(Date = as.Date(c("2015-09-01", "2015-09-01", "2015-09-01")),
Shop = c("Asda", "Tesco", "foo"),
Item = c("Apple", "Pear", "Orange"),
ProductKey = c("0f-7c-32-9c65","7c-e9-a0-a11c", "blah"),
Price = c(2.20, 1.70, 3.00), stringsAsFactors = FALSE)
df2014$key <- paste0(strftime(df2014$Date, "%m"),
strftime(df2014$Date, "%d"),
df2014$Shop,
df2014$Item,
df2014$ProductKey)
df2015$key <- paste0(strftime(df2015$Date, "%m"),
strftime(df2015$Date, "%d"),
df2015$Shop,
df2015$Item,
df2015$ProductKey)
df2015$price_2014 <- df2014$Price[match(df2015$key, df2014$key)]
df2015$price_ratio <- df2015$Price/df2015$price_2014
df2015
'按月merge',以及使用條件,以獲得不同 – Wen