[R] Trying to get the prior value of a record from a data.frame . . . data.frame
Sorkin, John
j@ork|n @end|ng |rom @om@um@ry|@nd@edu
Fri Nov 29 02:25:42 CET 2024
I need to write code that will give me the previous value of from a data.frame. I have written the following code using the shift function from data.table . It does not work. I hope someone can help me correct the code.
###########################
# Try to understand shift #
###########################
if(!require(data.table)) install.packages("data.table")
library(data.table)
# Create data
x <- data.frame(Id=rep(1:10),num=rep(11:20))
cat("This is the input data.frame used in the code below","\n")
x
for (i in 1:10) {
cat("x[i,num]",x[i,"num"],"\n")
# Get previous value of x[i,"num"]
zoop<-shift(x[i,"num"], n=1L, type="lag")
cat("Previous value of x[,num]=",zoop,"\n")
}
###############################
# END Try to understand shift #
###############################
Thank you,
John
John David Sorkin M.D., Ph.D.
Professor of Medicine, University of Maryland School of Medicine;
Associate Director for Biostatistics and Informatics, Baltimore VA Medical Center Geriatrics Research, Education, and Clinical Center;
PI Biostatistics and Informatics Core, University of Maryland School of Medicine Claude D. Pepper Older Americans Independence Center;
Senior Statistician University of Maryland Center for Vascular Research;
Division of Gerontology and Paliative Care,
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
Cell phone 443-418-5382
More information about the R-help
mailing list