r select values below and after a certain value in a dataframe

后端 未结 1 1009
夕颜
夕颜 2021-01-23 10:39

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.

相关标签:
1条回答
  • 2021-01-23 10:45
    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
    
    0 讨论(0)
提交回复
热议问题