So I have a data frame of dates and a response column and I have a vector of differences to show the change over time for a set of new values I want to add to the response column. How can I do some sort of matrix subtraction to take the values from the vector and difference them from the existing values in the column to get new values?
The data frame is set up like this:
data <- data.frame(seq(from = 2001, to = 2020, 1))
data$y <- (runif(20, 1, 10))
data$y[11:20] <- NA
colnames(data)[1] <- "Year"
the vector of differences looks like this:
vector <- runif(10, -1, 1)
So the desired output would look like this:
Year y
2011 y10+vector1 = y11
2012 y11+vector2 = y12
2013 y12+vector3 = y13
and so on...
One possibility would be to use the cumsum
function:
set.seed(1)
data <- data.frame(seq(2001, 2020, 1))
data$y <- (runif(20, 1, 10))
data$y[11:20] <- NA
colnames(data)[1] <- "Year"
myvector <- runif(10, -1, 1)
data$y[11:20] <- data$y[10] + cumsum(myvector)
Also, it is good practice to set a random seed (with set.seed
) when working with random numbers.