dat <- data.frame(subject = rep(1:2, each = 6),
day = rep(1:2, each = 3),
obs = rep(1:6, times = 2),
time = as.POSIXct(c("2024-01-01 09:01:00", "2024-01-01 12:05:00",
"2024-01-01 15:14:00", "2024-01-02 09:03:00",
"2024-01-02 12:21:00", "2024-01-02 15:03:00",
"2024-01-01 09:02:00", "2024-01-01 12:09:00",
"2024-01-01 15:06:00", "2024-01-02 09:02:00",
"2024-01-02 12:15:00", "2024-01-02 15:06:00")),
pos = c(6, 7, 5, 8, NA, 7, 4, NA, 5, 4, 5, 3),
neg = c(2, 3, 2, 5, 3, 4, 6, 4, 6, 4, NA, 8))
# Example 1a: Lagged variable for 'pos'
lagged(dat$pos, id = dat$subject, day = dat$day)
# Example 1b: Alternative specification
lagged(dat[, c("pos", "subject", "day")], id = "subject", day = "day")
# Example 1c: Alternative specification using the 'data' argument
lagged(pos, data = dat, id = "subject", day = "day")
# Example 2a: Lagged variable for 'pos' and 'neg'
lagged(dat[, c("pos", "neg")], id = dat$subject, day = dat$day)
# Example 2b: Alternative specification using the 'data' argument
lagged(pos, neg, data = dat, id = "subject", day = "day")
# Example 3: Lag-2 variables for 'pos' and 'neg'
lagged(pos, neg, data = dat, id = "subject", day = "day", lag = 2)
# Example 4: Lagged variable and time difference variable
lagged(pos, neg, data = dat, id = "subject", day = "day", time = "time")
# Example 5: Lagged variables and time difference variables,
# name variables
lagged(pos, neg, data = dat, id = "subject", day = "day", time = "time",
name = c("p.lag1", "n.lag1"), name.td = c("p.diff", "n.diff"))
# Example 6: NA observations excluded from the data frame
dat.excl <- dat[!is.na(dat$pos), ]
# Number of observation not taken into account, i.e.,
# - observation 4 used as lagged value for observation 6 for subject 1
# - observation 1 used as lagged value for observation 3 for subject 2
lagged(pos, data = dat.excl, id = "subject", day = "day")
# Number of observation taken into account by specifying the 'ob' argument
lagged(pos, data = dat.excl, id = "subject", day = "day", obs = "obs")
Run the code above in your browser using DataLab