I'm trying to do a predictive analysis where metrics from year x will predict year x+1.
I want to do the equivalent of an UPDATE query in SQL using R. If I have data like this:
x <- c("Randy Watson", "Cleo McDowell", "Darryl Jenks", "Jaffe Joffer",
"Randy Watson", "Cleo McDowell", "Darryl Jenks", "Jaffe Joffer",
"Randy Watson", "Cleo McDowell", "Darryl Jenks", "Jaffe Joffer")
y <- c("2012", "2012", "2012", "2012",
"2013", "2013", "2013", "2013",
"2014", "2014", "2014", "2014")
z <- c(100, 50, 75, 0,
110, 75, 0, 25,
125, 25, 10, 50)
df <- data.frame(x, y, z)
colnames(df) <- c("Name", "Year", "Sales")
print(df)
Name Year Sales
1 Randy Watson 2012 100
2 Cleo McDowell 2012 50
3 Darryl Jenks 2012 75
4 Jaffe Joffer 2012 0
5 Randy Watson 2013 110
6 Cleo McDowell 2013 75
7 Darryl Jenks 2013 0
8 Jaffe Joffer 2013 25
9 Randy Watson 2014 125
10 Cleo McDowell 2014 25
11 Darryl Jenks 2014 10
12 Jaffe Joffer 2014 50
I want the final output to look like:
print(df)
Name YearX YearX1
1 Randy Watson 100 110
2 Cleo McDowell 50 75
3 Darryl Jenks 75 0
4 Jaffe Joffer 0 25
...
How can I do this in R? I know how to do this in SQL (though I'd rather not use sqldf unless its the best way).
Thanks.
Edit: The solution below isn't quite what I'm looking for. While it works if there are only two years my data has 10 years. I don't need Name, Year1, Year2, Year3, etc... I just want Name, YearX, YearX+1. Sorry if I was unclear about that.