我有以下两个数据帧:
Date <- seq(as.Date("2013/1/1"), by = "day", length.out = 46)
x <-data.frame(Date)
x$discharge <- c("1000","1100","1200","1300","1400","1200","1300","1300","1200","1100","1200","1200","1100","1400","1200","1100","1400","1000","1100","1200","1300","1400","1200","1300","1300","1200","1100","1200","1200","1100","1400","1200","1100","1400","1000","1100","1200","1300","1400","1200","1300","1300","1200","1100","1200","1200")
x$discharge <- as.numeric(x$discharge)
和
Date_from <- c("2013-01-01","2013-01-15","2013-01-21","2013-02-10")
Date_to <- c("2013-01-07","2013-01-20","2013-01-25","2013-02-15")
y <- data.frame(Date_from,Date_to)
y$concentration <- c("1.5","2.5","1.5","3.5")
y$Date_from <- as.Date(y$Date_from)
y$Date_to <- as.Date(y$Date_to)
y$concentration <- as.numeric(y$concentration)
我正在尝试根据日期范围x
到y
,根据数据帧Date_from
中每一行的数据,从数据帧Date_to
中的日排放中计算出平均排放量在数据帧y
中。请注意,2013年1月1日至2013年1月14日之间和2013年1月26日至2013年2月9日之间,数据帧y
中的度量存在差距。该差距是由于在此期间未进行任何测量而造成的。由于我使用以下代码来计算y
中每个日期范围的平均排放量,因此这一差距让我头疼。
rng <- cut(x$Date, breaks=c(y$Date_from, max(y$Date_to),
include.lowest=T))
range<-cbind(x,rng)
discharge<-aggregate(cbind(mean=x$discharge)~rng, FUN=mean)
但是,如果您在数据框range
中检查范围,则将2013-01-01至2013-01-07的范围扩展到2013-01-14,但我只需要将其扩展到2013-01 -07,然后稍作休息,直到下一个范围从2013-01-15开始。
答案 0 :(得分:4)
您可以尝试使用tidyverse
。
library(tidyverse)
y %>%
split(seq_along(1:nrow(.))) %>%
map(~filter(x, between(Date, .$Date_from, .$Date_to)) %>%
summarise(Mean=mean(discharge))) %>%
bind_rows() %>%
bind_cols(y,.)
Date_from Date_to concentration Mean
1 2013-01-01 2013-01-07 1.5 1214.286
2 2013-01-15 2013-01-20 2.5 1166.667
3 2013-01-21 2013-01-25 1.5 1300.000
4 2013-02-10 2013-02-15 3.5 1216.667
仅使用此代码,您可以看到值和组。
y %>%
split(seq_along(1:nrow(.))) %>%
map(~filter(x, between(Date, .$Date_from, .$Date_to)))
答案 1 :(得分:2)
这是一个base
的答案:
helper <- merge(x, y)
helper <- helper[helper$Date >= helper$Date_from & helper$Date <= helper$Date_to, ]
aggregate(helper$discharge,
list(Date_from = helper$Date_from,
Date_to = helper$Date_to),
FUN = 'mean')
Date_from Date_to x
1 2013-01-01 2013-01-07 1214.286
2 2013-01-15 2013-01-20 1166.667
3 2013-01-21 2013-01-25 1300.000
4 2013-02-10 2013-02-15 1216.667