我有一个有日期在一行的数据: ej:
CULTIVAR/ START DATE / END DATE
x / 11.02.2020 / 11.02.2021和另一个日期和环境变量列表的Dataframe:
Date Humidity
01.01.2020 / 80
02.01.2020 / 85
03.01.2020 / 90我需要一个代码来将Ambiental添加到第一个dataframe中,这是几天来根据比赛进行的。因此,如果我需要从开始日期到品种X的结束日期的平均湿度,它会到达第二个数据,迭代这些数据,加工它们,并在第一个数据中添加平均湿度。
发布于 2022-02-17 19:35:34
一种使用R将mean_humidity添加到第一个数据帧的方法,方法是检查来自df2的日期是否在df1的给定开始日期和结束日期之内
示例数据
df1
cul start end
1 x 2020-02-11 2020-03-22
2 y 2020-03-11 2020-03-12
3 z 2020-04-11 2020-04-11
4 o 2020-05-11 2020-05-11
df2
date humidity
1 2020-02-11 34
2 2020-03-11 45
3 2020-03-12 26
4 2020-03-13 65
5 2020-04-11 67
6 2020-05-15 78使用
df1$mean_humidity <- rowMeans(
sapply(seq_along(df2$date), function(x)
ifelse(df2$date[x] >= df1$start &
df2$date[x] <= df1$end,
df2$humidity[x], NA)
), na.rm=T)
df1
cul start end mean_humidity
1 x 2020-02-11 2020-03-22 42.5
2 y 2020-03-11 2020-03-12 35.5
3 z 2020-04-11 2020-04-11 67.0
4 o 2020-05-11 2020-05-11 NaNdput()数据
df1 <- structure(list(cul = c("x", "y", "z", "o"), start = structure(c(18303,
18332, 18363, 18393), class = "Date"), end = structure(c(18343,
18333, 18363, 18393), class = "Date")), class = "data.frame", row.names = c(NA,
-4L))
df2 <- structure(list(date = structure(c(18303, 18332, 18333, 18334,
18363, 18397), class = "Date"), humidity = c(34, 45, 26, 65,
67, 78)), row.names = c(NA, -6L), class = "data.frame")https://stackoverflow.com/questions/71117030
复制相似问题