I have a list of data frames similar to the reprex below but with 100+ columns:
# reproducible example
df <- data.frame(
Name = c("Name1", "Name2", "Name3", "Name4", "Name5"),
Date = c("2018-01-01", "2018-01-02"),
Value1 = c(rnorm(5, 2, 3), rnorm(5, 4, 1)),
Value2 = c(rnorm(5, 12, 4), rnorm(5, 5, 8)),
Value3 = c(rnorm(5, 22, 13), rnorm(5, 7, 10))
)
# transform data frame into list
df <- split(df, df$Name)
For each data frame in the list, I would like to replace the last row with values from the one prior row. For example, for each data frame in the list, I would like to replace [2, 3:5] with [1, 3:5].
> tail(df[["Name1"]], n = 2)
Name Date Value1 Value2 Value3
1 Name1 2018-01-01 0.9184539 15.658510 29.219707
2 Name1 2018-01-02 3.8875463 3.628546 9.777399
I'm not sure if transforming my data frame into a list is the best way to go about this so any other suggestions are welcome. I tried tackling this as outlined below but my attempt only replaces the last row in the data frame with the second to last row.
My Attempt
# reproducible example
df <- data.frame(
Name = c("Name1", "Name2", "Name3", "Name4", "Name5"),
Date = c("2018-01-01", "2018-01-02"),
Value1 = c(rnorm(5, 2, 3), rnorm(5, 4, 1)),
Value2 = c(rnorm(5, 12, 4), rnorm(5, 5, 8)),
Value3 = c(rnorm(5, 22, 13), rnorm(5, 7, 10))
)
# arrange by Name and Date
df <- df %>% dplyr::arrange(Name, Date)
# attempt to replace
df[length(df$Name), c(3:5)] <- df[length(df$Name)-1, c(3:5)]
# result
tail(df, n = 4)
> tail(df, n = 4)
Name Date Value1 Value2 Value3
7 Name4 2018-01-01 3.242383 -11.44217 -1.215688
8 Name4 2018-01-02 -4.042093 18.18184 1.544271
9 Name5 2018-01-01 -1.930195 13.18662 18.889372
10 Name5 2018-01-02 -1.930195 13.18662 18.889372