简体   繁体   中英

R match with previous observation

How can I match the latest available observation for HPG with the previous observation for HAR? I am looking for a general solution that would allow me to select the n-th previous observation. Below an example.

library(zoo)
library(ggplot2)
library(ggrepel)
library(data.table)


# scatterplot preparation
set.seed(123)
country <- c("AT", "BE", "NL", "DE", "FR", "IT", "ES", "PT", "AT", "BE", "NL", "DE", "FR", "IT", "ES", "PT")
year <- as.yearqtr(c("2019 Q1", "2019 Q1","2019 Q1", "2019 Q1", "2019 Q1", "2019 Q1", "2019 Q1", "2019 Q1", "2019 Q2", "2019 Q2", "2019 Q2", "2019 Q2", "2019 Q2", "2019 Q2", "2019 Q2", "2019 Q2"))

HPG <- runif(16, min=0, max=5)

HAR <- runif(16, min=-1, max=3)
HAR[c(11,13)] <- NA

df <- data.frame(country, year, HPG, HAR)
df <- as.data.table(df)
df

We can get the index of last observation by group with .I , then subtract 1 from that index to return the previous row index

i1 <- df[order(year), .I[.N], .(country)]$V1
df[, HPG[i1] == HAR[i1-1]]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM