Gwen Yang
Gwen Yang

Reputation: 146

Add a new column that equals to another column one index before in R

I have a dataframe like this:

date <- as.Date(c('2020-01-01','2020-01-02','2020-01-03'))
value <- c(5,6,7)
df <- data.frame(date, value)

I want to create other 2 columns val_1,val_2 that equals to respectively value and val_1 that are one index before:

date        value   val_1   val_2
2020-01-01    5      NA      NA
2020-01-01    6      5       NA
2020-01-01    7      6       5

how do I do that?

Upvotes: 0

Views: 63

Answers (1)

jay.sf
jay.sf

Reputation: 72623

You could use sapply to manipulate the lengths.

df <- setNames(cbind(df, sapply(1:2, function(i) 
  c(rep(NA, i), x[-(length(x):(length(x)-(i-1)))]))),
  c(names(df), paste0("val_", 1:2)))
df
#         date value val_1 val_2
# 1 2020-01-01     5    NA    NA
# 2 2020-01-02     6     5    NA
# 3 2020-01-03     7     6     5

Upvotes: 1

Related Questions