给定纬度和经度的按月平均数据?

时间:2017-10-21 18:55:58

标签: r

我有一个包含以下标题和示例数据的表

Lat            Long           Date          Value.
30.497478    -87.880258      01/01/2016       10
30.497478    -87.880258      01/02/2016       15
30.497478    -87.880258      01/05/2016       20
33.284928    -85.803608      01/02/2016       10
33.284928    -85.803608      01/03/2016       15
33.284928    -85.803608      01/05/2016       20

我想按月为特定地点平均价值列。

因此示例输出将是

Lat              Long         Month      Avg Value
30.497478      -87.880258    January     15

2 个答案:

答案 0 :(得分:2)

您可以尝试以下操作,但它首先使用包Month修改数据框,添加额外的列zoo

library(zoo)

dat$Month <- as.yearmon(as.Date(dat$Date, "%m/%d/%Y"))

aggregate(Value. ~ Lat + Long + Month, dat, mean)
#       Lat      Long    Month Value.
#1 30.49748 -87.88026 jan 2016     15
#2 33.28493 -85.80361 jan 2016     15

如果您不想更改原始数据,请复制dat2 <- dat并更改副本。

数据

dat <-
structure(list(Lat = c(30.497478, 30.497478, 30.497478, 33.284928, 
33.284928, 33.284928), Long = c(-87.880258, -87.880258, -87.880258, 
-85.803608, -85.803608, -85.803608), Date = structure(c(1L, 2L, 
4L, 2L, 3L, 4L), .Label = c("01/01/2016", "01/02/2016", "01/03/2016", 
"01/05/2016"), class = "factor"), Value. = c(10L, 15L, 20L, 10L, 
15L, 20L)), .Names = c("Lat", "Long", "Date", "Value."), class = "data.frame", row.names = c(NA, 
-6L))

修改
如果要计算多个统计信息,可以定义一个计算它们的函数并返回命名向量并在aggregate中调用它,如下所示。

stat <- function(x){
    c(Mean = mean(x), Median = median(x), SD = sd(x))
}
agg <- aggregate(Value. ~ Lat + Long + Month, dat, stat)
agg <- cbind(agg[1:3], as.data.frame(agg[[4]]))
agg
#       Lat      Long    Month Mean Median SD
#1 30.49748 -87.88026 jan 2016   15     15  5
#2 33.28493 -85.80361 jan 2016   15     15  5

答案 1 :(得分:2)

使用dplyrlubridate的解决方案。

library(dplyr)
library(lubridate)

dt2 <- dt %>%
  mutate(Date = mdy(Date), Month = month(Date)) %>%
  group_by(Lat, Long, Month) %>%
  summarise(`Avg Value` = mean(Value))
dt2
# A tibble: 2 x 4
# Groups:   Lat, Long [?]
       Lat      Long Month `Avg Value`
     <dbl>     <dbl> <dbl>       <dbl>
1 30.49748 -87.88026     1          15
2 33.28493 -85.80361     1          15