You need joins, and something like tidyr::fill
:
library(dplyr)
library(tidyr)
x %>% mutate(slopezz = slopezz[1:n()]) %>%
right_join(veh, by = c('psi' = 'Tim')) %>%
fill(slopezz, .direction = 'up')
# psi slopezz
# 1 169.7 -2.1920
# 2 169.8 -2.1920
# 3 169.9 -2.1920
# 4 170.0 -2.1920
# 5 170.1 -2.1920
# 6 170.2 -2.1920
# . ... ...
Note that this will leave the last four values as NA
as you’re fill
ing up. If you want to then fill
down, just add on %>% fill(slopezz)
.
Data
x <- structure(list(psi = c(171.4, 171.8, 175.1, 175.7, 176.3, 177.8,
178.7, 180.1, 181.5, 182.4, 183.8, 184.8)), .Names = "psi", class = "data.frame", row.names = c(NA, -12L))
slopezz <- c(-2.192, 0.7034, 0.6113, -1.254, 0.7513, 2.325, 0.0791, -0.9713,
1.101, 1.949, -1.429, 2.25, 0.8775)
veh <- structure(list(Tim = c(169.7, 169.8, 169.9, 170, 170.1, 170.2,
170.3, 170.4, 170.5, 170.6, 170.7, 170.8, 170.9, 171, 171.1,
171.2, 171.3, 171.4, 171.5, 171.6, 171.7, 171.8, 171.9, 172,
172.1, 172.2, 172.3, 172.4, 172.5, 172.6, 172.7, 172.8, 172.9,
173, 173.1, 173.2, 173.3, 173.4, 173.5, 173.6, 173.7, 173.8,
173.9, 174, 174.1, 174.2, 174.3, 174.4, 174.5, 174.6, 174.7,
174.8, 174.9, 175, 175.1, 175.2, 175.3, 175.4, 175.5, 175.6,
175.7, 175.8, 175.9, 176, 176.1, 176.2, 176.3, 176.4, 176.5,
176.6, 176.7, 176.8, 176.9, 177, 177.1, 177.2, 177.3, 177.4,
177.5, 177.6, 177.7, 177.8, 177.9, 178, 178.1, 178.2, 178.3,
178.4, 178.5, 178.6, 178.7, 178.8, 178.9, 179, 179.1, 179.2,
179.3, 179.4, 179.5, 179.6, 179.7, 179.8, 179.9, 180, 180.1,
180.2, 180.3, 180.4, 180.5, 180.6, 180.7, 180.8, 180.9, 181,
181.1, 181.2, 181.3, 181.4, 181.5, 181.6, 181.7, 181.8, 181.9,
182, 182.1, 182.2, 182.3, 182.4, 182.5, 182.6, 182.7, 182.8,
182.9, 183, 183.1, 183.2, 183.3, 183.4, 183.5, 183.6, 183.7,
183.8, 183.9, 184, 184.1, 184.2, 184.3, 184.4, 184.5, 184.6,
184.7, 184.8, 184.9, 185, 185.1, 185.2)), .Names = "Tim", row.names = c(NA,
-156L), class = "data.frame")
solved How to add a variable in a data frame using another variable for indices?