Às 01:25 de 29/11/2024, Sorkin, John escreveu:
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



______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Hello,

If you want to shift an entire vector, you don't need the loop, pass the vector itself to data.table::shift.



x <- data.frame(Id=rep(1:10),num=rep(11:20))

data.table::shift(x[["num"]], n = 1L)
#>  [1] NA 11 12 13 14 15 16 17 18 19
data.table::shift(x[, "num"], n = 1L)
#>  [1] NA 11 12 13 14 15 16 17 18 19


Hope this helps,

Rui Barradas


--
Este e-mail foi analisado pelo software antivírus AVG para verificar a presença 
de vírus.
www.avg.com

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to