对于R中的几个数据帧,返回与给定日期最接近的行
我有9个不同长度的时间序列数据帧,每个数据帧用于不同的位置。我试图找到一种方法来输入一个日期,并让R同时输出包含所有数据帧中最接近我输入日期的日期的行 现在,我一次做一个:对于R中的几个数据帧,返回与给定日期最接近的行,r,date,time-series,R,Date,Time Series,我有9个不同长度的时间序列数据帧,每个数据帧用于不同的位置。我试图找到一种方法来输入一个日期,并让R同时输出包含所有数据帧中最接近我输入日期的日期的行 现在,我一次做一个: #bring in data MNT <- read_excel("MNT_temporal.xlsx") #change date format MNT$date <- ymd_hms(MNT$date) #specifying input date date <- ymd_hms
#bring in data
MNT <- read_excel("MNT_temporal.xlsx")
#change date format
MNT$date <- ymd_hms(MNT$date)
#specifying input date
date <- ymd_hms("2017-09-11 15:47:35")
#find which row is closest to input date
which.min(abs(date - MNT$date))
[1] 6 #R returns row with closest date
MNT[6,] #view data
# A tibble: 1 x 4
date number.of.positives percent_inundated avg_depth_inundated
<dttm> <dbl> <dbl> <dbl>
1 2017-09-11 15:45:00 0 0 NA
#引入数据
这样怎么样
my_function<-function(filename){
#bring in data
file <- read_excel(filename)
#change date format
file$date <- ymd_hms(file$date)
#specifying input date
date <- ymd_hms("2017-09-11 15:47:35")
#find which row is closest to input date
rowindex<-which.min(abs(date - file$date))
return(file[rowindex,])
}
alllocations<-paste0(c("MNT","MUT","MLT","MST","MOL","PNT","PUT","PLT","PST"),"_temporal.xlsx")
savedates<-data.frame("date"=rep(0,length(alllocations)),"number.of.positives"=0, "percent_inundated"=0, "avg_depth_inundated"=0)
for(i in 1:length(alllocations)){
savedates[i,]<-my_function(alllocations[i])
}
my_函数
#bring in data
MUT <- read_excel("MUT_temporal.xlsx")
MLT <- read_excel("MLT_temporal.xlsx")
MST <- read_excel("MST_temporal.xlsx")
MOL <- read_excel("MOL_temporal.xlsx")
PNT <- read_excel("PNT_temporal.xlsx")
PUT <- read_excel("PUT_temporal.xlsx")
PLT <- read_excel("PLT_temporal.xlsx")
PST <- read_excel("PST_temporal.xlsx")
my_function<-function(filename){
#bring in data
file <- read_excel(filename)
#change date format
file$date <- ymd_hms(file$date)
#specifying input date
date <- ymd_hms("2017-09-11 15:47:35")
#find which row is closest to input date
rowindex<-which.min(abs(date - file$date))
return(file[rowindex,])
}
alllocations<-paste0(c("MNT","MUT","MLT","MST","MOL","PNT","PUT","PLT","PST"),"_temporal.xlsx")
savedates<-data.frame("date"=rep(0,length(alllocations)),"number.of.positives"=0, "percent_inundated"=0, "avg_depth_inundated"=0)
for(i in 1:length(alllocations)){
savedates[i,]<-my_function(alllocations[i])
}