I have three columns and in fourth column i want a lag of third column. How to do this in R
For example
uid timestamp operation
1 24-04-12 logged-in
2 25-06-13 view content
1 31-05-10 delete
But i want to use lag function as we do in SAS and want output as below
uid timestamp operation lag
1 24-04-12 logged-in
2 25-06-13 view content logged-in
3 31-05-10 delete view content
I have lag function using zoo package ,but it is not happening , how to do this in R?? Any guidance will be much appreciated.
When using functions specific to the zoo
package (eg ?lag.zoo
), you need to make sure the data you are operating on is a zoo
object:
operation <- c("logged-in","view current", "delete")
lag(zoo(operation),-1,na.pad=TRUE)
# 1 2 3
# <NA> logged-in view current
lag(zoo(operation),1,na.pad=TRUE)
# 1 2 3
#view current delete <NA>
Otherwise, using base R, head
(and tail
) can get you there:
# match the 1 and -1 to how big you want your lag:
c(rep(NA,1),head(operation,-1))
#[1] NA "logged-in" "view current"
c(tail(operation,-1),rep(NA,1))
#[1] "view current" "delete" NA
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.