Select Value from Previous Row of data.table in R (Example Code)
In this tutorial you’ll learn how to select values from the previous row of a data.table in the R programming language.
Setting up the Example
install.packages("data.table") # Install data.table package library("data.table") # Load data.table |
install.packages("data.table") # Install data.table package library("data.table") # Load data.table
my_dt <- data.table(x = 10:15, # Construct data.table in R y = 1:6) my_dt # Print data.table in RStudio console # x y # 1: 10 1 # 2: 11 2 # 3: 12 3 # 4: 13 4 # 5: 14 5 # 6: 15 6 |
my_dt <- data.table(x = 10:15, # Construct data.table in R y = 1:6) my_dt # Print data.table in RStudio console # x y # 1: 10 1 # 2: 11 2 # 3: 12 3 # 4: 13 4 # 5: 14 5 # 6: 15 6
Example: Use Previous Row of data.table for Calculation
my_dt_new <- my_dt # Duplicate data.table my_dt_new[ , z := x + shift(y)] # Add columns using shift() my_dt_new # Show new data.table in RStudio console # x y z # 1: 10 1 NA # 2: 11 2 12 # 3: 12 3 14 # 4: 13 4 16 # 5: 14 5 18 # 6: 15 6 20 |
my_dt_new <- my_dt # Duplicate data.table my_dt_new[ , z := x + shift(y)] # Add columns using shift() my_dt_new # Show new data.table in RStudio console # x y z # 1: 10 1 NA # 2: 11 2 12 # 3: 12 3 14 # 4: 13 4 16 # 5: 14 5 18 # 6: 15 6 20
Related Articles
Please find some related R programming language tutorials on topics such as RStudio, extracting data, and groups in the following list: