i have a question how to select certain values from a table. I have a table with times and values and i want to get the row below and after a certain time.
Example-Data.
value_before <- example_df[which(example_df$time=="09:45")-1, ]$value
value_after <- example_df[which(example_df$time=="09:45")+1, ]$value
# This could become a function
return_values <- function(df,cutoff) {
value_before <- df[which(df$time==cutoff)-1, ]$value
value_after <- df[which(df$time==cutoff)+1, ]$value
return(list(value_before, value_after))
}
return_values(exmaple_df, "09:15")
# A solution for a large dataset.
library(data.table)
df <- data.frame(time = 1:1000000, value = rnorm(1000000))
# create a couple of offsets
df$nvalue <- c(df$value[2:dim(df)[1]],NA)
df$pvalue <- c(NA,df$value[2:dim(df)[1]])
new_df <- data.table(df)
setkey(new_df,"time")
new_df[time==10]
time value pvalue nvalue
[1,] 10 -0.8488881 -0.1281219 -0.5741059
> new_df[time==1234]
time value pvalue nvalue
[1,] 1234 -0.3045015 0.708884 -0.5049194