海量数据集 - 按月份和位置计算的平均值

问题描述 投票:0回答:1

我非常感谢您对一些数据进行排序以减少我拥有的海量数据集(近 2600 行)的时间自相关性方面的帮助。我确信对于 tidyverse 这样的东西来说这可能是一件相当简单的事情,但我对使用 R 进行数据清理还很陌生,需要学习。

这是一个非常大的表格,包含昆虫学数据……昆虫陷阱计数、经度、纬度、日期和大量环境变量(一些是数字,一些是分类)。一个假设的(小得多)的例子是:

df <- data.frame(
insects = round(runif(20)*100),
long = c(rep(22.4,5), rep(18.4,5), rep(21.8,5), rep(20.1,5)),
lat = c(rep(-34.1,5), rep(-34.4,5), rep(-33.8,5), rep(-33.7,5)),
land = c(rep("AG8",5), rep("GA6",5), rep("HE1",5), rep("JA2",5)),
temp = round(runif(20)*15),
NDVI = c(rep(c(48032730,48493073,48449380,48423773,48420000),4)),
precip = round(runif(20)*15),
date = lubridate::as_date(rep(c("2006-01-15", "2006-01-25", "2006-01-04", "2007-02-15", "2007-02-18", "2006-01-15", "2008-02-20", "2008-02-01", "2009-04-08", "2009-04-19"),2)))

我想创建一个新的数据框,其中每个相同的位置(经度/纬度)在一个日历月中有多个计数,都合并到一行中,其中昆虫计数和环境变量都是该月的平均值(每个位置的分类值应该相同。

因此,对于上面的数据框示例,我最终会得到以下结果,而不是 20 行: 第一个位置有 2 行(2006 年 1 月和 2007 年 2 月) 第二个位置 3 行(2006 年 1 月、2008 年 2 月、2009 年 4 月) 第三个位置 2 行(2006 年 1 月和 2007 年 2 月) 第四个位置 3 行(2006 年 1 月、2008 年 2 月、2009 年 4 月)

感谢您的帮助

dataframe dplyr tidyverse tidyr data-cleaning
1个回答
0
投票

首先,创建一个名为month_year的新列。
接下来,按位置(经度、纬度)和月份_年份进行分组,并计算平均值。

library(dplyr)

df <- df %>%
  mutate(month_year = format(date, "%Y-%m"))

df_averaged <- df %>%
  group_by(long, lat, month_year, land) %>%
  summarise(insects = mean(insects),
            temp = mean(temp),
            NDVI = mean(NDVI),
            precip = mean(precip))

df_averaged <- df_averaged %>%
  mutate(month_year = as.Date(paste0(month_year, "-01")))

print(df_averaged)

> print(df_averaged)
# A tibble: 10 × 8
# Groups:   long, lat, month_year [10]
    long   lat month_year land  insects  temp      NDVI precip
   <dbl> <dbl> <date>     <chr>   <dbl> <dbl>     <dbl>  <dbl>
 1  18.4 -34.4 2006-01-01 GA6      75   11    48032730    1   
 2  18.4 -34.4 2008-02-01 GA6      93.5  6.5  48471226.   6.5 
 3  18.4 -34.4 2009-04-01 GA6      11.5 13    48421886.   9   
 4  20.1 -33.7 2006-01-01 JA2      38   13    48032730    6   
 5  20.1 -33.7 2008-02-01 JA2      45   11    48471226.   7.5 
 6  20.1 -33.7 2009-04-01 JA2      56.5 11    48421886.   6   
 7  21.8 -33.8 2006-01-01 HE1      45.7  4    48325061    7.67
 8  21.8 -33.8 2007-02-01 HE1      28    7    48421886.   7   
 9  22.4 -34.1 2006-01-01 AG8      68.3  9.33 48325061    8.67
10  22.4 -34.1 2007-02-01 AG8      56    8.5  48421886.   9   
© www.soinside.com 2019 - 2024. All rights reserved.