问题
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.Frame.
Time Value
02:51 0.08033405
05:30 0.43456738
09:45 0.36052075
14:02 0.45013807
18:55 0.05745870
....# and so on
Time is coded as character, but can be formatted. Now i have for example the time "6:15" and want to get the values of the time before and after this time from the table (0.43456738 and 0.36052075). The database is in fact quite huge and i have a lot of time values. Anyone has a nice suggestion how to accomplish this?
thanks Curlew
回答1:
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
来源:https://stackoverflow.com/questions/10952092/r-select-values-below-and-after-a-certain-value-in-a-dataframe