lundi 22 juin 2020

Advanced question: Create a for loop that contains conditions for rows and columns to compute the rate of change in R

I have data for different years, with different months, in different towns & prices like so

 i | hrvyear |   m  |   town      |   price   | (expected rate of change)
1  |  1270   |  5   | Chesterford |   80      |    NA
2  |  1270   |  6   | Chesterford |   64      |  -20 %
3  |  1270   |  7   | Lopham      |   74      |    NA
4  |  1274   |  12  | Lopham      |   74      |    NA
5  |  1275   |  1   | Lopham      |   78      |   5,4054 % 
6  |  1275   |  2   | Lopham      |   59      |  -24,3589 %
7  |  1275   |  3   | Lopham      |   61      |   3,3898 %
8  |  1275   |  5   | Lopham      |   68      |    NA

And I want to add the rate of change of the price of the previous month, under the conditions that it is in the same year (or from December to January of the following year); and in the same city.

structure(list(hrvyear = c(1270, 1270, 1272, 1272, 1275, 1275
), m = c(5, 12, 2, 4, 2, 3), town = c("Chesterford", "Chesterford", 
"Lopham", "Lopham", "Lopham", "Lopham"), `mean(price)` = c(80, 
64, 74, 78, 59, 61)), row.names = c(NA, -6L), groups = structure(list(
    hrvyear = c(1270, 1270, 1272, 1272, 1275, 1275), m = c(5, 
    12, 2, 4, 2, 3), .rows = structure(list(1L, 2L, 3L, 4L, 5L, 
        6L), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", 
    "list"))), row.names = c(NA, 6L), class = c("tbl_df", "tbl", 
"data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"))

Aucun commentaire:

Enregistrer un commentaire