Forge
Forge

Reputation: 1677

shift a column with lagged data from other column and enlarge data frame as needed

I have a data frame with values and I need a new column with shifted values some rows down but data frame has to get more rows to accommodate the shifted data.

What I've got so far:

df <- data.frame(day=1:5,value=floor(runif(5, min=0, max=101))) 

>  df %>% dplyr::mutate(value2=dplyr::lag(value,n=2, default = 0)) 

  day value value2
1   1    19      0
2   2    78      0
3   3    18     19
4   4    14     78
5   5    10     18

Expected result:

  day value value2
1   1    19      0
2   2    78      0
3   3    18     19
4   4    14     78
5   5    10     18
6   6     0     14
7   7     0     10

Stuck on making the data frame grow the needed rows.

Upvotes: 0

Views: 143

Answers (2)

Shree
Shree

Reputation: 11140

Here's a way with dplyr -

df %>%
  bind_rows(
    tail(df, 2) %>% 
      mutate(day = day + 2, value = 0)
  ) %>% 
  mutate(value2 = lag(value, 2, default = 0))

  day value value2
1   1    19      0
2   2    78      0
3   3    18     19
4   4    14     78
5   5    10     18
6   6     0     14
7   7     0     10

Upvotes: 1

AdamO
AdamO

Reputation: 4910

Use a merge. Create the "target" dataset with however many rows you want, fill in NA values with 0, then remap the lagged value onto "value2". It's useful to store "lag" as a variable, at the risk of being more verbose.

have <- data.frame(
  day=  1:5,
  value = c(19, 78, 18, 14, 10),
  value2 = c(0, 0, 19, 78, 18)
)
target <- data.frame(
  day=1:7
)

want <- merge(have, target, by='day', all=T)
want[is.na(want)] <- 0
lag <- 2

## just one way of mapping a lagged response
want$value2 <- c(rep(0, lag), rev(rev(want$value)[-{1:lag}]))

Upvotes: 1

Related Questions