Last updated: 2021-05-17

Checks: 7 0

Knit directory: booksn_ppm/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20210517) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version fd92f89. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    data/.DS_Store
    Ignored:    data/data_raw/

Untracked files:
    Untracked:  data/coplas2019.csv

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/preparaDatos.Rmd) and HTML (docs/preparaDatos.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd fd92f89 Antonio J Perez-Luque 2021-05-17 add preparacion de datos

library("tidyverse")
library("here")
library("finch")
library("sf")
library("sp")
library("readxl")
library("DT")

Datos de parcelas

  • Leemos el archivo que publicamos en GBIF

  • Utilizamos un shape con las parcelas, al cual le calculamos en su momento la elevación mínima, máxima y promedio de la parcela (este shape no se publicó; se llama rodales_stats.shp)

  • Realizamos una clasificación de las parcelas en altitud (elevF):

    • elev_mean <= 600: 0verylow;
    • elev_mean >600 & elev_mean <=1200: 1low
    • elev_mean >1200 & elev_mean <=1700: 2medium
    • elev_mean >1700: 3high
  • Generamos un dataset con los siguientes campos:

    • código de parcela,
    • area (ha)
    • perímetro
    • provincia
    • elevacion (min, max, mean, elevF)
    • lat, long
# https://ipt.gbif.es/archive.do?r=coplas&v=2.4
f <- finch::dwca_read("https://ipt.gbif.es/archive.do?r=coplas&v=2.4")

# Read the data files
eventRaw <- read_delim(f$data[1], delim = "\t") # event.txt
occRaw <- read_delim(f$data[2], delim = "\t") # occurrence.txt
mofRaw <- read_delim(f$data[3], delim = "\t") # extendedmeasurementorfact.txt

rodales <- st_read(here::here("data/data_raw/geoinfo/rodales_stats.shp")) 
Reading layer `rodales_stats' from data source `/Users/ajpelu/Google Drive/MS/books/2021_SN/booksn_ppm/data/data_raw/geoinfo/rodales_stats.shp' using driver `ESRI Shapefile'
Simple feature collection with 4389 features and 7 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bbox:           xmin: -7.436747 ymin: 36.04137 xmax: -1.875561 ymax: 38.61815
geographic CRS: WGS 84
rodal_elev <- rodales %>% st_drop_geometry() %>% 
  rename_all(tolower) %>% 
  dplyr::select(code = codigo, 
                perim = perimetro, 
                elev_mean = mean) %>% 
  mutate(across(where(is.numeric), round, 2))
  

parcelas <- eventRaw %>% 
  mutate(code = stringr::str_remove(eventID, "(\\-).*"),
         area_ha = sampleSizeValue/10000) %>% 
  dplyr::select(code,
                area_ha,
                prov = stateProvince, 
                elev_min = minimumElevationInMeters,
                elev_max = maximumElevationInMeters,
                lat = decimalLatitude,
                long = decimalLongitude) %>% unique() %>% 
  inner_join(rodal_elev) %>% 
  mutate(
    elevF = case_when(
      elev_mean <= 600 ~ "0verylow",
      elev_mean >600 & elev_mean <=1200 ~ "1low",
      elev_mean >1200 & elev_mean <=1700 ~ "2medium",
      elev_mean >1700 ~ "3high"
    )
  )

Datos de infestación

  • Leemos los datos de infestación (COPLAS) de las parcelas desde 1992 hasta 2019
# Read all sheets from excel 
path <- here::here("data/data_raw/Grados_Infestacion_1992_2019.xlsx")
raw_infesta <- path %>% 
  excel_sheets() %>% 
  set_names() %>% 
  map_df(read_excel, path = path) 

names(raw_infesta) <- c("code","infestacion","year")

Corregimos algunos errores en la nomenclatura de las parcelas. Parece que hay un problema con que algunas parcelas están llamadas de diferente forma con “-” y sin “-”

raw_infesta <- raw_infesta %>% 
  mutate(code = stringr::str_remove_all(code, "-"))

¿Cuantos plots?

length(unique(raw_infesta$code))
[1] 4828

Parece que hay duplicados. Vamos a buscarlos: - Creamos un campo codeyear (code+year) - Buscamos duplicados, esto es para una misma fecha + parcela varios valores de infestacion

duplicados <- raw_infesta %>% 
  unite("codeyear", c(code,year), sep="-", remove=FALSE) %>% 
  group_by(codeyear) %>% 
  count() %>% 
  filter(n>1) %>% 
  separate(codeyear, c("code", "year"), sep="-", remove=FALSE) 

parcelas_duplicadas <- duplicados %>% 
  dplyr::select(code) %>% unique()

Vamos a usar los datos que ya teníamos publicados en GBIF, que parece que tenian solucionado el filtrado de datos y le vamos a añadir nuevos datos (desde 2015 a la actualidad)

infesta2015 <- mofRaw %>% 
  mutate(
    code = stringr::str_remove(id, "(\\-).*")) %>% 
  dplyr::select(
  code,
  infestacion = measurementValue,
  year = measurementDeterminedDate) %>%
  pivot_wider(names_from = year, 
              values_from = infestacion)

De los datos nuevos filtramos > 2015

raw_infesta2019 <- raw_infesta %>% filter(year > 2015) 

duplicados2019 <- raw_infesta2019 %>% 
  filter(year > 2015) %>% 
  unite("codeyear", c(code,year), sep="-", remove=FALSE) %>% 
  group_by(codeyear) %>% 
  count() %>% 
  filter(n>1) %>% 
  separate(codeyear, c("code", "year"), sep="-", remove=FALSE) 

parcelas_duplicadas2019 <- duplicados2019 %>% 
  dplyr::select(code) %>% unique()

infesta2019 <- raw_infesta2019 %>% 
  filter(year > 2015) %>%
  pivot_wider(names_from = year, 
              values_from = infestacion, 
              values_fn = {min})
coplas <- infesta2015 %>% 
  left_join(infesta2019) 

Datos de Especies de pinos

Hemos llevado a cabo la asignación de los pinos por dos vías:

  • (1). Cruzar cobertura de coplas con cobertura de pinos (issue)

Hemos usado, datos de formaciones de: https://laboratoriorediam.cica.es/geonetwork/srv/spa/catalog.search#/metadata/a25e289b-4d4d-49fc-af06-b64adf29e81b

ph <- st_read(here::here("data/data_raw/geoinfo/dist_pinus/Phalepensis.shp")) %>% 
  mutate(pinus = "halepensis")

rodales_t <- st_make_valid(rodales) %>% st_transform(crs = st_crs(ph)) 

parcelas_centroid <- parcelas %>% dplyr::select(code, lat, long) %>% 
  st_as_sf(coords = c("long", "lat"), crs = 4326) %>% 
  st_transform(crs = st_crs(ph)) 
# st_write(parcelas_centroid, here::here(here::here("data_raw/geoinfo/parcelas_centroid.shp")), 
#          append = FALSE)

pn <- st_read(here::here("data/data_raw/geoinfo/dist_pinus/Pnigra.shp")) %>% 
  mutate(pinus = "nigra")
pp <- st_read(here::here("data/data_raw/geoinfo/dist_pinus/Ppinaster.shp")) %>% 
  mutate(pinus = "pinaster")
ps <- st_read(here::here("data/data_raw/geoinfo/dist_pinus/Psylvestris.shp")) %>% 
  mutate(pinus = "sylvestris")
ppinea <- st_read(here::here("data/data_raw/geoinfo/dist_pinus/Ppinea.shp")) %>% 
  mutate(pinus = "pinea")
pr <- st_read(here::here("data/data_raw/geoinfo/dist_pinus/Pradiata.shp")) %>% 
  mutate(pinus = "radiata")
pc <- st_read(here::here("data/data_raw/geoinfo/dist_pinus/Pcanariensis.shp")) %>% 
  mutate(pinus = "canariensis")


iph <- st_intersection(st_make_valid(ph), rodales_t) %>% st_drop_geometry() %>% 
  dplyr::select(Codigo, pinus) %>% unique() 

ipp <- st_intersection(st_make_valid(pp), rodales_t) %>% st_drop_geometry() %>% 
    dplyr::select(Codigo, pinus) %>% unique() 
ips <- st_intersection(st_make_valid(ps), rodales_t) %>% st_drop_geometry() %>% 
    dplyr::select(Codigo, pinus) %>% unique() 
ipn <- st_intersection(st_make_valid(pn), rodales_t) %>% st_drop_geometry() %>% 
    dplyr::select(Codigo, pinus) %>% unique() 
ippinea <- st_intersection(st_make_valid(ppinea), rodales_t) %>% st_drop_geometry() %>% 
    dplyr::select(Codigo, pinus) %>% unique() 
ipc <- st_intersection(st_make_valid(pc), rodales_t) %>% st_drop_geometry() %>% 
    dplyr::select(Codigo, pinus) %>% unique() 
ipr <- st_intersection(st_make_valid(pr), rodales_t) %>% st_drop_geometry() %>% 
    dplyr::select(Codigo, pinus) %>% unique() 


u <- bind_rows(iph, ipp, ips, ipn, ipc, ipr, ippinea)

u <- u %>% mutate(v = 1) %>% 
  pivot_wider(names_from = pinus, values_from = v)


i <- iph %>% dplyr::select(Codigo, pinus) %>% unique()
    1. Usar datos procedentes de la base de datos antigua (proporcionada por L. Cayuela)
load(here::here("data/data_raw/mapa_rodales.RData"))

parcela_sp <- mapa.rodales@data %>% dplyr::select(code = N.rodal, sp = Especie)

Le añadimos los pinos a la parcela

coplas_sp <- coplas %>% inner_join(parcela_sp) %>% 
  inner_join(parcelas) %>% 
  dplyr::relocate(code, prov, area_ha, sp, elev_mean, elev_min, elev_max, elevF, perim, lat, long, `1993`:`2015`, `2016`, `2017`, `2018`, `2019`)

write_csv(coplas_sp, here::here("data/coplas2019.csv"))
DT::datatable(coplas_sp)

sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.3

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] DT_0.17         readxl_1.3.1    sp_1.4-5        sf_0.9-7       
 [5] finch_0.4.0     here_1.0.1      forcats_0.5.1   stringr_1.4.0  
 [9] dplyr_1.0.4     purrr_0.3.4     readr_1.4.0     tidyr_1.1.2    
[13] tibble_3.0.6    ggplot2_3.3.3   tidyverse_1.3.0 workflowr_1.6.2

loaded via a namespace (and not attached):
 [1] httr_1.4.2         sass_0.3.1         jsonlite_1.7.2     modelr_0.1.8      
 [5] bslib_0.2.4        assertthat_0.2.1   cellranger_1.1.0   yaml_2.2.1        
 [9] lattice_0.20-41    pillar_1.4.7       backports_1.2.1    glue_1.4.2        
[13] uuid_0.1-4         digest_0.6.27      promises_1.2.0.1   rvest_0.3.6       
[17] EML_2.0.4          colorspace_2.0-0   htmltools_0.5.1.1  httpuv_1.5.5      
[21] pkgconfig_2.0.3    broom_0.7.4        haven_2.3.1        scales_1.1.1      
[25] whisker_0.4        later_1.1.0.1      emld_0.5.1         git2r_0.28.0      
[29] generics_0.1.0     ellipsis_0.3.1     withr_2.4.1        lazyeval_0.2.2    
[33] cli_2.3.0          magrittr_2.0.1     crayon_1.4.1       evaluate_0.14     
[37] fs_1.5.0           xml2_1.3.2         class_7.3-18       tools_4.0.2       
[41] data.table_1.13.6  hms_1.0.0          lifecycle_1.0.0    V8_3.4.0          
[45] munsell_0.5.0      reprex_1.0.0       compiler_4.0.2     jquerylib_0.1.3   
[49] e1071_1.7-4        jqr_1.2.0          rlang_0.4.10       classInt_0.4-3    
[53] units_0.6-7        grid_4.0.2         jsonld_2.2         rstudioapi_0.13   
[57] htmlwidgets_1.5.3  rappdirs_0.3.3     crosstalk_1.1.1    rmarkdown_2.6.6   
[61] gtable_0.3.0       DBI_1.1.1          curl_4.3           R6_2.5.0          
[65] lubridate_1.7.10   knitr_1.31         rprojroot_2.0.2    KernSmooth_2.23-18
[69] hoardr_0.5.2       stringi_1.5.3      Rcpp_1.0.6         vctrs_0.3.6       
[73] dbplyr_2.1.0       tidyselect_1.1.0   xfun_0.20