我有一个数据集,它有天气变量的每日平均值,第二个数据集有动物观测的每小时计数。我想把这些数据集结合起来,这样我就可以建立一个模型来评估天气变量对计数的混合影响。更复杂的是,数据格式不同,观测有一个单独的月、日和小时列,天气以一个Dd/M/-yyyy HH:mm列开始。如果必要的话,我可以在原始数据中手工修正这个问题,以便进行观测。
如何在R中做到最好?样本数据:
date <- c("1/1/2020 3:00", "1/2/2020 3:00","1/3/2020 3:00")
temp <- c(18, 25, 10)
press <- c(.25, .5, 1.25)
met <- data.frame(date, press, temp)
month <- c(1, 1, 1, 1, 1, 1, 1, 1, 1)
day <- c(1, 1, 1, 2, 2, 2, 3, 3,3)
hour <- c(10, 11, 12, 10, 11, 12,10, 11, 12)
obs <- c( 14, 88, 67, 198, 3, 54, 2, 80, 36)
counts <- data.frame(month, day, hour, obs)
编辑以将每日观察分散到所有时间。
下面是一些使用dplyr
和lubridate
的代码。函数mutate
在数据帧中创建新列,parse_date_time
创建具有数据时间类的对象,floor_date
查找观测发生的日期。
函数group_by
和summarise
将观测值组合起来,以创建给定日期的平均值。
利用CCD_ 8将两者结合起来。
我假设2020年。
library(lubridate)
library(dplyr)
date <- c("1/1/2020 3:00", "1/2/2020 3:00","1/3/2020 3:00")
temp <- c(18, 25, 10)
press <- c(.25, .5, 1.25)
met <-
data.frame(date, press, temp) %>%
mutate(dmyhm = parse_date_time(date, orders='m/d/y H:M')) %>%
mutate(ymd = floor_date(dmyhm, unit = 'day')) %>%
select(ymd, press, temp)
month <- c(1, 1, 1, 1, 1, 1, 1, 1, 1)
day <- c(1, 1, 1, 2, 2, 2, 3, 3,3)
hour <- c(10, 11, 12, 10, 11, 12,10, 11, 12)
obs <- c( 14, 88, 67, 198, 3, 54, 2, 80, 36)
counts <-
data.frame(month, day, hour, obs) %>%
mutate(dmyhm = parse_date_time(paste0(month, '/', day, '/', '2020 ', hour), orders='m/d/y H')) %>%
mutate(ymd = floor_date(dmyhm, unit='day'))
# a full join causes extra rows to be added where they
# don't exist in the smaller data set
combined <-
counts %>%
full_join(met, by = 'ymd') %>%
select(month, day, hour, obs, press, temp)
combined
# month day hour obs press temp
# 1 1 1 10 14 0.25 18
# 2 1 1 11 88 0.25 18
# 3 1 1 12 67 0.25 18
# 4 1 2 10 198 0.50 25
# 5 1 2 11 3 0.50 25
# 6 1 2 12 54 0.50 25
# 7 1 3 10 2 1.25 10
# 8 1 3 11 80 1.25 10
# 9 1 3 12 36 1.25 10