简体   繁体   中英

Dataframe in R: add new columns, data is from current dataframe

Suppose I have the following df,

df <- data.frame(
  month  =  12:1,
  value = c(2,3,4,2,3,4,2,3,4,2,3,4)
    )

which contains value for each of the past 12 months. Now I want to add two new columns to record values for past 2 months, for month 12-3, like this:

df2 <- data.frame(
  month  =  12:3,
  value_0 = c(2,3,4,2,3,4,2,3,4,2),
  value_1 = c(3,4,2,3,4,2,3,4,2,3),
  value_2 = c(4,2,3,4,2,3,4,2,3,4))

This algorithm, when the df gets larger and I want to add n new columns for the past n values, can't be done simply by manually typing... So I wonder, is there a shortcut way to do this? Thank you!

shift from data.table and take n as a vector of values

library(data.table)
na.omit(setDT(df)[, paste0("value_", 1:2) := shift(value, type = "lead", 
     1:2)])

-output

    month value value_1 value_2
    <int> <num>   <num>   <num>
 1:    12     2       3       4
 2:    11     3       4       2
 3:    10     4       2       3
 4:     9     2       3       4
 5:     8     3       4       2
 6:     7     4       2       3
 7:     6     2       3       4
 8:     5     3       4       2
 9:     4     4       2       3
10:     3     2       3       4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM