to this tibble `csmib_lag1` add the column `date` from this tibble `csmib` as a date index, hence it should be the first column of `csmib_lag1` in r

You can use bind_cols() from dplyr package to add the date column as the first column in csmib_lag1.

Assuming that both csmib and csmib_lag1 have a column named date that contains the same dates in the same order:

main.r
library(dplyr)
library(tibble)

# create sample data
csmib <- tibble(
  date = as.Date("2021-01-01") + 0:4,
  value = c(10, 20, 30, 40, 50)
)

# add a lagged column
csmib_lag1 <- csmib %>%
  mutate(lag1 = lag(value, 1))

# bind date column as the first column of csmib_lag1
csmib_lag1 <- bind_cols(date = csmib$date, csmib_lag1)

# print the result
csmib_lag1
360 chars
19 lines

Output:

main.r
# A tibble: 5 x 3
  date       value  lag1
  <date>     <dbl> <dbl>
1 2021-01-01    10    NA
2 2021-01-02    20    10
3 2021-01-03    30    20
4 2021-01-04    40    30
5 2021-01-05    50    40
193 chars
9 lines

Here, the bind_cols() function adds the date column as the first column of csmib_lag1.

related categories

gistlibby LogSnag