Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

R match with previous observation

$
0
0

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

Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>