├── .Rbuildignore ├── .Rhistory ├── cleanRfield.Rproj ├── DESCRIPTION ├── man ├── sampleField.Rd ├── rasterField.Rd ├── sdField.Rd ├── boundaryField.Rd ├── filterField.Rd ├── bufferField.Rd └── cropField.Rd ├── NAMESPACE ├── inst └── CITATION ├── R ├── fct_sampleField.R ├── fct_rasterField.R ├── fct_bufferField.R ├── fct_boundaryField.R ├── fct_cropField.R ├── fct_sdField.R └── fct_filterField.R ├── tut_code.R ├── LICENSE └── README.md /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | -------------------------------------------------------------------------------- /.Rhistory: -------------------------------------------------------------------------------- 1 | library(cleanRfield) 2 | library(cleanRfield) 3 | -------------------------------------------------------------------------------- /cleanRfield.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | BuildType: Package 16 | PackageUseDevtools: Yes 17 | PackageInstallArgs: --no-multiarch --with-keep.source 18 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: cleanRfield 2 | Title: A tool for cleaning and filtering data spatial points from agricultural field trials 3 | Version: 2.0.0 4 | Authors@R: 5 | c(person(given = "Filipe",family = "Matias",role = c("cre", "aut"),email = "filipematias23@gmail.com"), 6 | person("Hunter","Smith",role = "aut",email = "huntersmith@ufl.edu")) 7 | Description: A compilation of functions to filter spacial points from agricultural field trials. 8 | License: GPL-2 9 | Encoding: UTF-8 10 | Roxygen: list(markdown = TRUE) 11 | RoxygenNote: 7.2.3 12 | Imports: 13 | methods, 14 | terra, 15 | smoothr, 16 | units, 17 | grDevices, 18 | graphics, 19 | stats 20 | -------------------------------------------------------------------------------- /man/sampleField.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fct_sampleField.R 3 | \name{sampleField} 4 | \alias{sampleField} 5 | \title{Sample data points within specified field.} 6 | \usage{ 7 | sampleField(field, shape = NULL, size = 0.1, cex = 1) 8 | } 9 | \arguments{ 10 | \item{field}{SpatVector. The field to be sampled.} 11 | 12 | \item{shape}{a specific area inside the field to be sampled. If shape=NULL, all field data will be sampled.} 13 | 14 | \item{size}{the proportion of original data to be sampled (must be values between 0 and 1).} 15 | 16 | \item{cex}{point size. Please check \code{help("points")}.} 17 | } 18 | \value{ 19 | the sampled field is returned in form SpatVector. 20 | } 21 | \description{ 22 | This function samples a specified SpatVector, reducing the data size. 23 | } 24 | \details{ 25 | sampleField 26 | } 27 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(boundaryField) 4 | export(bufferField) 5 | export(cropField) 6 | export(filterField) 7 | export(rasterField) 8 | export(sampleField) 9 | export(sdField) 10 | importFrom(grDevices,grey) 11 | importFrom(graphics,locator) 12 | importFrom(graphics,par) 13 | importFrom(methods,as) 14 | importFrom(methods,is) 15 | importFrom(smoothr,drop_crumbs) 16 | importFrom(stats,sd) 17 | importFrom(terra,aggregate) 18 | importFrom(terra,as.polygons) 19 | importFrom(terra,buffer) 20 | importFrom(terra,crop) 21 | importFrom(terra,crs) 22 | importFrom(terra,draw) 23 | importFrom(terra,erase) 24 | importFrom(terra,ext) 25 | importFrom(terra,fillHoles) 26 | importFrom(terra,lines) 27 | importFrom(terra,plot) 28 | importFrom(terra,rast) 29 | importFrom(terra,rasterize) 30 | importFrom(terra,simplifyGeom) 31 | importFrom(units,set_units) 32 | -------------------------------------------------------------------------------- /man/rasterField.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fct_rasterField.R 3 | \name{rasterField} 4 | \alias{rasterField} 5 | \title{Make a raster from shapefile data} 6 | \usage{ 7 | rasterField(field, res = 1, trait = NULL, shape = NULL, cex = 1) 8 | } 9 | \arguments{ 10 | \item{field}{SpatVector. The shapefile to be converted to raster.} 11 | 12 | \item{res}{resolution to make the raster layer.} 13 | 14 | \item{trait}{vector with the traits to be converted to raster.} 15 | 16 | \item{shape}{a specific area inside the field to be converted to raster. If shape=NULL, all field data will be converted.} 17 | 18 | \item{cex}{point size. Please check \code{help("points")}.} 19 | } 20 | \value{ 21 | A raster stack in form SpatRaster. 22 | } 23 | \description{ 24 | This function makes raster layers from shapefile data. 25 | } 26 | \details{ 27 | rasterField 28 | } 29 | -------------------------------------------------------------------------------- /man/sdField.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fct_sdField.R 3 | \name{sdField} 4 | \alias{sdField} 5 | \title{Filter spatial vector data based on standard deviation.} 6 | \usage{ 7 | sdField(field, shape = NULL, trait = NULL, value = 1, cex = 1) 8 | } 9 | \arguments{ 10 | \item{field}{SpatVector. The field to be filtered.} 11 | 12 | \item{shape}{a specific area inside the field to be filtered. If shape=NULL, all field data will be used for filtering.} 13 | 14 | \item{trait}{a vector of the traits to be used as filter criteria.} 15 | 16 | \item{value}{threshold value of standard deviation to filter the trait data below (must be numeric).} 17 | 18 | \item{cex}{point size. Please check \code{help("points")}.} 19 | } 20 | \value{ 21 | A SpatVector filtered by standard deviation. 22 | } 23 | \description{ 24 | This function filters the original data based on standard deviation of traits. 25 | } 26 | \details{ 27 | sdField 28 | } 29 | -------------------------------------------------------------------------------- /man/boundaryField.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fct_boundaryField.R 3 | \name{boundaryField} 4 | \alias{boundaryField} 5 | \title{Create a boundary shapefile from raster data} 6 | \usage{ 7 | boundaryField( 8 | field, 9 | draw = FALSE, 10 | col = "red", 11 | cex = 1, 12 | threshold = 1000, 13 | tolerance = 2e-04 14 | ) 15 | } 16 | \arguments{ 17 | \item{field}{SpatRaster. Field to be converted to boundary shapefile.} 18 | 19 | \item{draw}{use TRUE to draw field boundaries.} 20 | 21 | \item{col}{line color.} 22 | 23 | \item{cex}{point size. Please check \code{help("points")}.} 24 | 25 | \item{threshold}{area (m^2) of small polygons, below which will be removed.} 26 | 27 | \item{tolerance}{boundary simplification - minimum distance between nodes in units of the crs (i.e. degrees for long/lat)} 28 | } 29 | \value{ 30 | A simplified boundary as SpatVector. 31 | } 32 | \description{ 33 | This function produces a simplified boundary shapefile from raster data. 34 | } 35 | \details{ 36 | boundaryField 37 | } 38 | -------------------------------------------------------------------------------- /man/filterField.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fct_filterField.R 3 | \name{filterField} 4 | \alias{filterField} 5 | \title{Filter spatial vector data based on value} 6 | \usage{ 7 | filterField( 8 | field, 9 | shape = NULL, 10 | trait = NULL, 11 | value = NULL, 12 | cropAbove = NULL, 13 | cex = 1 14 | ) 15 | } 16 | \arguments{ 17 | \item{field}{SpatVector. The field to be filtered.} 18 | 19 | \item{shape}{a specific area inside the field to be filtered. If shape=NULL, all field data will be used for filtering.} 20 | 21 | \item{trait}{a vector of the traits to be used as filter criteria.} 22 | 23 | \item{value}{threshold value to filter the trait data (must be numeric).} 24 | 25 | \item{cropAbove}{if TRUE all data above the 'value' will be retained. if FALSE all data below the 'value' will be retained.} 26 | 27 | \item{cex}{point size. Please check \code{help("points")}.} 28 | } 29 | \value{ 30 | the filtered SpatVector. 31 | } 32 | \description{ 33 | This function filters spatial vector data based on trait value. 34 | } 35 | \details{ 36 | filterField 37 | } 38 | -------------------------------------------------------------------------------- /inst/CITATION: -------------------------------------------------------------------------------- 1 | note <- sprintf("R package version %s", meta$Version) 2 | 3 | citHeader("The following are references to the package cleanRfield. You should also reference the individual methods used, as detailed in the reference section of the help files for each function.") 4 | 5 | bibentry(bibtype="article", 6 | title = "{cleanRfield}: A tool for cleaning and filtering data spacial points from agricultural field trials in {R}", 7 | author = c(person(c("Filipe", "I."), "Matias"),person(c("", ""), ""),person(c("", ""), "")), 8 | journal = "Crop Science", 9 | year = "2021", 10 | pages = "", 11 | url = "" 12 | ) 13 | 14 | bibentry(bibtype="Manual", 15 | title = "{cleanRfield}: A tool for cleaning and filtering data spacial points from agricultural field trials in {R}", 16 | author = c(person(c("Filipe", "I."), "Matias"),person(c("", ""), ""),person(c("", ""), "")), 17 | year = "", 18 | url = "", 19 | note = note 20 | ) 21 | 22 | citFooter('To get Bibtex entries use: x<-citation("cleanRfield"); toBibtex(x)') 23 | -------------------------------------------------------------------------------- /man/bufferField.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fct_bufferField.R 3 | \name{bufferField} 4 | \alias{bufferField} 5 | \title{Create a buffer shapefile within the target geometry} 6 | \usage{ 7 | bufferField(shape, value = c(-1), field = NULL, cex = 1) 8 | } 9 | \arguments{ 10 | \item{shape}{SpatVector. The target geometry to be buffered. Object of class.} 11 | 12 | \item{value}{value of the buffer - measured in mapunits. Must be numeric and negative.} 13 | 14 | \item{field}{SpatVector. If input, field cropped by target geometry included in output. If field=NULL, only the buffer will be generated.} 15 | 16 | \item{cex}{point size. Please check \code{help("points")}.} 17 | } 18 | \value{ 19 | If field=NULL, the buffer SpatVector is returned. If field provided, list with two elements is returned: 20 | \itemize{ 21 | \item \code{newShape} is the buffer SpatVector. 22 | \item \code{newField} is the field cropped using the buffered shape, also a SpatVector. 23 | } 24 | } 25 | \description{ 26 | This function produces a buffer within the target geometry by a specified value. 27 | } 28 | \details{ 29 | bufferField 30 | } 31 | -------------------------------------------------------------------------------- /man/cropField.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fct_cropField.R 3 | \name{cropField} 4 | \alias{cropField} 5 | \title{Crop a specified field from original data} 6 | \usage{ 7 | cropField(field, shape = NULL, nPolygon = 1, nPoint = 4, cex = 1) 8 | } 9 | \arguments{ 10 | \item{field}{SpatVector.} 11 | 12 | \item{shape}{a specified shape for cropping. If shape=NULL, the user will be prompted to draw one or more polygon(s).} 13 | 14 | \item{nPolygon}{number of polygons.} 15 | 16 | \item{nPoint}{number of points per polygon (4 >= nPoint <= 50).} 17 | 18 | \item{cex}{point size. Please check \code{help("points")}.} 19 | } 20 | \value{ 21 | A list with three elements: 22 | \itemize{ 23 | \item \code{shape} is the specified cropped geometry, in format \code{SpatVector}. 24 | \item \code{cropField} is the original object area without the cropped shape, in format \code{SpatVector}. 25 | \item \code{selectedField} the cropped data (contained within the cropped shape), in format \code{SpatVector}. 26 | } 27 | } 28 | \description{ 29 | This function crops selected regions from the original data using an existing shapefile or user-drawn polygon. 30 | } 31 | \details{ 32 | cropField 33 | } 34 | -------------------------------------------------------------------------------- /R/fct_sampleField.R: -------------------------------------------------------------------------------- 1 | #' sampleField 2 | #' 3 | #' @title Sample data points within specified field. 4 | #' 5 | #' @description This function samples a specified SpatVector, reducing the data size. 6 | #' 7 | #' @param field SpatVector. The field to be sampled. 8 | #' @param shape a specific area inside the field to be sampled. If shape=NULL, all field data will be sampled. 9 | #' @param size the proportion of original data to be sampled (must be values between 0 and 1). 10 | #' @param cex point size. Please check \code{help("points")}. 11 | #' 12 | #' @importFrom terra crop plot 13 | #' @importFrom graphics par 14 | #' @importFrom methods as is 15 | #' 16 | #' 17 | #' @return the sampled field is returned in form SpatVector. 18 | #' 19 | #' 20 | #' @export 21 | sampleField <- function (field, shape = NULL, size = 0.1, cex = 1) 22 | { 23 | print(paste("Field class is ", class(field)[1], sep = "")) 24 | if (size > 1 | size < 0) { 25 | stop("'size' must be a value between 0.0 and 1.0") 26 | } 27 | par(mfrow = c(1, 2)) 28 | terra::plot(field, col = "bisque3", main = "Original", pch = 20, 29 | cex = cex) 30 | if (!is.null(shape)) { 31 | field <- crop(x = field, y = shape) 32 | terra::plot(shape, col = "gold4", add = T, pch = 20, cex = cex) 33 | } 34 | Out <- field[sample(1:dim(field)[1], dim(field)[1] * size), 35 | ] 36 | terra::plot(Out, col = "gold4", main = "Reduced", pch = 20, cex = cex) 37 | if (!is.null(shape)) { 38 | terra::plot(shape, add = T) 39 | } 40 | par(mfrow = c(1, 1)) 41 | return(Out) 42 | } 43 | -------------------------------------------------------------------------------- /R/fct_rasterField.R: -------------------------------------------------------------------------------- 1 | #' rasterField 2 | #' 3 | #' @title Make a raster from shapefile data 4 | #' 5 | #' @description This function makes raster layers from shapefile data. 6 | #' 7 | #' @param field SpatVector. The shapefile to be converted to raster. 8 | #' @param res resolution to make the raster layer. 9 | #' @param trait vector with the traits to be converted to raster. 10 | #' @param shape a specific area inside the field to be converted to raster. If shape=NULL, all field data will be converted. 11 | #' @param cex point size. Please check \code{help("points")}. 12 | #' 13 | #' @importFrom terra plot crs crop rasterize rast ext 14 | #' @importFrom grDevices grey 15 | #' @importFrom methods as is 16 | #' 17 | #' 18 | #' @return A raster stack in form SpatRaster. 19 | #' 20 | #' 21 | #' @export 22 | rasterField <- function (field, res = 1, trait = NULL, shape = NULL, cex = 1) 23 | { 24 | print(paste("Field class is ", class(field)[1], sep = "")) 25 | if (!is.null(shape)) { 26 | par(mfrow = c(1, 2)) 27 | terra::plot(field, col = "bisque3", main = "Original", pch = 20, 28 | cex = cex) 29 | terra::plot(shape, col = "gold4", add = T, pch = 20, cex = cex) 30 | field <- terra::crop(x = field, y = shape) 31 | } 32 | Data <- values(field) 33 | if (is.null(trait)) { 34 | stop(paste("Choose one or more 'trait' for filtering in this list: ", 35 | paste(colnames(Data), collapse = ", "), ".", sep = "")) 36 | } 37 | r <- terra::rast(ext(field), resolution = res) 38 | Out <- NULL 39 | for (t in trait){ 40 | Out1 = terra::rasterize(x = field, y = r, t, fun = mean) 41 | crs(Out1) <- crs(field) 42 | Out <- c(Out, Out1) 43 | } 44 | Out <- rast(Out) 45 | set.names(Out, trait) 46 | terra::plot(Out, col = grey(100:1/100)) 47 | if (!is.null(shape)) { 48 | terra::plot(shape, add = T) 49 | } 50 | 51 | par(mfrow = c(1, 1)) 52 | return(Out) 53 | } 54 | -------------------------------------------------------------------------------- /R/fct_bufferField.R: -------------------------------------------------------------------------------- 1 | #' bufferField 2 | #' 3 | #' @title Create a buffer shapefile within the target geometry 4 | #' 5 | #' @description This function produces a buffer within the target geometry by a specified value. 6 | #' 7 | #' @param shape SpatVector. The target geometry to be buffered. Object of class. 8 | #' @param value value of the buffer - measured in mapunits. Must be numeric and negative. 9 | #' @param field SpatVector. If input, field cropped by target geometry included in output. If field=NULL, only the buffer will be generated. 10 | #' @param cex point size. Please check \code{help("points")}. 11 | #' 12 | #' @importFrom terra buffer crs 13 | #' @importFrom graphics par 14 | #' @importFrom methods as is 15 | #' 16 | #' @return If field=NULL, the buffer SpatVector is returned. If field provided, list with two elements is returned: 17 | #' \itemize{ 18 | #' \item \code{newShape} is the buffer SpatVector. 19 | #' \item \code{newField} is the field cropped using the buffered shape, also a SpatVector. 20 | #' } 21 | #' 22 | #' @export 23 | bufferField <- function (shape, value = c(-1), field = NULL, cex = 1) 24 | { 25 | if (!all(is.numeric(value))) { 26 | stop("'value' must be numeric.") 27 | } 28 | options(warn = -1) 29 | shapeB <- buffer(shape, value) 30 | crs(shapeB) <- crs(shape) 31 | options(warn = 0) 32 | title <- paste0("Filter on shape: \nBuffer = ", value) 33 | if (is.null(field)) { 34 | par(mfrow = c(1, 1)) 35 | terra::plot(shape, main = title) 36 | terra::plot(shapeB, add = T) 37 | Out = shapeB 38 | } 39 | if (!is.null(field)) { 40 | par(mfrow = c(1, 2)) 41 | terra::plot(shape, main = title) 42 | terra::plot(shapeB, add = T) 43 | filtered <- crop(x = field, y = shapeB) 44 | title <- paste0("Filter on data: \nBuffer = ", value) 45 | terra::plot(field, col = "bisque3", main = title, pch = 20, 46 | cex = cex) 47 | terra::plot(filtered, col = "gold4", add = T, pch = 20, cex = cex) 48 | Out = list(newShape = shapeB, newField = filtered) 49 | } 50 | par(mfrow = c(1, 1)) 51 | return(Out) 52 | } 53 | -------------------------------------------------------------------------------- /R/fct_boundaryField.R: -------------------------------------------------------------------------------- 1 | #' boundaryField 2 | #' 3 | #' @title Create a boundary shapefile from raster data 4 | #' 5 | #' @description This function produces a simplified boundary shapefile from raster data. 6 | #' 7 | #' @param field SpatRaster. Field to be converted to boundary shapefile. 8 | #' @param draw use TRUE to draw field boundaries. 9 | #' @param col line color. 10 | #' @param cex point size. Please check \code{help("points")}. 11 | #' @param threshold area (m^2) of small polygons, below which will be removed. 12 | #' @param tolerance boundary simplification - minimum distance between nodes in units of the crs (i.e. degrees for long/lat) 13 | #' 14 | #' @importFrom units set_units 15 | #' @importFrom terra simplifyGeom fillHoles aggregate as.polygons plot draw crs 16 | #' @importFrom smoothr drop_crumbs 17 | #' @importFrom grDevices grey 18 | #' @importFrom methods as is 19 | #' 20 | #' @return A simplified boundary as SpatVector. 21 | #' 22 | #' 23 | #' @export 24 | boundaryField <- function (field, draw = FALSE, col = "red", cex = 1, threshold = 1000, tolerance = 0.0002) 25 | { 26 | print(paste("Field class is ", class(field)[1], sep = "")) 27 | if (!draw) { 28 | if (!class(field) %in% c("SpatRaster")) { 29 | stop("For automatic boundary identification, 'boundaryField()' function requires a raster object. Please, use the function 'rasterField()' first or use 'draw=T' for drawing the boundary.") 30 | } 31 | par(mfrow = c(1, 2)) 32 | area_thresh <- units::set_units(threshold, m^2) 33 | shape <- simplifyGeom(smoothr::drop_crumbs(fillHoles(aggregate(as.polygons(field),fun=mean)), threshold = area_thresh), 34 | tolerance = tolerance) 35 | } 36 | if (draw) { 37 | par(mfrow = c(1, 3)) 38 | print("Draw field 'boundary' and press 'ESC' when done.") 39 | if (class(field) %in% c("SpatRaster")) { 40 | terra::plot(field, axes = FALSE, box = FALSE, col = grey(100:1/100), 41 | main = "Draw field 'boundary' and press 'ESC' when done") 42 | } 43 | if (!class(field) %in% c("SpatRaster")) { 44 | terra::plot(field, col = "bisque3", cex = cex, main = "Draw field 'boundary' and press 'ESC' when done") 45 | } 46 | shape <- draw(x="polygon", col = col, lwd = 1) 47 | } 48 | crs(shape) <- crs(field) 49 | 50 | if (class(field) %in% c("SpatRaster")) { 51 | terra::plot(field, col = grey(100:1/100), main = "Original") 52 | } 53 | if (!class(field) %in% c("SpatRaster")) { 54 | terra::plot(field, col = "gold4", main = "Original", cex = cex) 55 | } 56 | terra::plot(shape, add = T) 57 | terra::plot(shape, main = "Shapefile") 58 | par(mfrow = c(1, 1)) 59 | return(shape) 60 | } 61 | -------------------------------------------------------------------------------- /R/fct_cropField.R: -------------------------------------------------------------------------------- 1 | #' cropField 2 | #' 3 | #' @title Crop a specified field from original data 4 | #' 5 | #' @description This function crops selected regions from the original data using an existing shapefile or user-drawn polygon. 6 | #' 7 | #' @param field SpatVector. 8 | #' @param shape a specified shape for cropping. If shape=NULL, the user will be prompted to draw one or more polygon(s). 9 | #' @param nPolygon number of polygons. 10 | #' @param nPoint number of points per polygon (4 >= nPoint <= 50). 11 | #' @param cex point size. Please check \code{help("points")}. 12 | #' 13 | #' @importFrom terra plot crop erase lines 14 | #' @importFrom graphics par locator 15 | #' @importFrom methods as 16 | #' 17 | #' @return A list with three elements: 18 | #' \itemize{ 19 | #' \item \code{shape} is the specified cropped geometry, in format \code{SpatVector}. 20 | #' \item \code{cropField} is the original object area without the cropped shape, in format \code{SpatVector}. 21 | #' \item \code{selectedField} the cropped data (contained within the cropped shape), in format \code{SpatVector}. 22 | #' } 23 | #' 24 | #' 25 | #' @export 26 | cropField = function (field, shape = NULL, nPolygon = 1, nPoint = 4, cex = 1) 27 | { 28 | print(paste("Field class is ", class(field)[1], sep = "")) 29 | if (nPoint < 4 | nPoint > 50) { 30 | stop("nPoint must be >= 4 and <= 50") 31 | } 32 | par(mfrow = c(1, 3)) 33 | terra::plot(field, col = "bisque3", main = "Original", pch = 20, 34 | cex = cex) 35 | if (is.null(shape)) { 36 | for (np in 1:nPolygon) { 37 | print(paste("Select ", nPoint, " points around polygon #", 38 | np, " in the plots space.", sep = "")) 39 | c1 <- NULL 40 | for (i in 1:nPoint) { 41 | c1.1 <- locator(type = "p", n = 1, col = np, 42 | pch = 19) 43 | c1 <- rbind(c1, c(c1.1$x, c1.1$y)) 44 | } 45 | c1 <- rbind(c1, c1[1, ]) 46 | colnames(c1) <- c("x", "y") 47 | lines(c1, col = np, type = "l", lty = 2, lwd = 3) 48 | p1 <- vect(c1, type="polygons") 49 | if (np == 1) { 50 | shape <- p1 51 | } 52 | if (np != 1) { 53 | shape <- rbind(shape, p1) 54 | } 55 | } 56 | } 57 | r <- crop(x = field, y = shape) 58 | r1 <- erase(x = field, y = shape) 59 | terra::plot(r, add = T, col = "gold4", pch = 20, cex = cex) 60 | terra::plot(shape, add = T, pch = 20) 61 | terra::plot(r1, col = "bisque3", main = "cropField", pch = 20, 62 | cex = cex) 63 | terra::plot(r, col = "gold4", main = "selectedField", pch = 20, 64 | cex = cex) 65 | terra::lines(shape) 66 | 67 | Out <- list(shape = shape, cropField = r1, selectedField = r) 68 | par(mfrow = c(1, 1)) 69 | return(Out) 70 | } 71 | -------------------------------------------------------------------------------- /R/fct_sdField.R: -------------------------------------------------------------------------------- 1 | #' sdField 2 | #' 3 | #' @title Filter spatial vector data based on standard deviation. 4 | #' 5 | #' @description This function filters the original data based on standard deviation of traits. 6 | #' 7 | #' @param field SpatVector. The field to be filtered. 8 | #' @param shape a specific area inside the field to be filtered. If shape=NULL, all field data will be used for filtering. 9 | #' @param trait a vector of the traits to be used as filter criteria. 10 | #' @param value threshold value of standard deviation to filter the trait data below (must be numeric). 11 | #' @param cex point size. Please check \code{help("points")}. 12 | #' 13 | #' @importFrom terra crop plot 14 | #' @importFrom graphics par 15 | #' @importFrom methods as is 16 | #' @importFrom stats sd 17 | #' 18 | #' 19 | #' @return A SpatVector filtered by standard deviation. 20 | #' 21 | #' 22 | #' @export 23 | sdField <- function (field, shape = NULL, trait = NULL, value = 1, cex = 1) 24 | { 25 | Data <- values(field) 26 | if (is.null(trait)) { 27 | stop(paste("Choose one or more 'trait' for filtering in this list: ", 28 | paste(colnames(Data), collapse = ", "), ".", sep = "")) 29 | } 30 | if (!all(trait %in% colnames(Data))) { 31 | stop(paste("'trait' is not in the list: ", paste(colnames(Data), 32 | collapse = ", "), ".", sep = "")) 33 | } 34 | if (!all(is.numeric(value))) { 35 | stop(paste("Choose one numeric value as a treshold/crop for each 'trait' in this list: ", 36 | paste(trait, collapse = ", "), ".", sep = "")) 37 | } 38 | if (length(value) != length(trait)) { 39 | stop(paste("'value' must be the same length of 'trait': ", 40 | length(trait), ".", sep = "")) 41 | } 42 | filtered <- field 43 | par(mfrow = c(1, length(trait) + 1)) 44 | terra::plot(field, col = "bisque3", main = "Original", pch = 20, 45 | cex = cex) 46 | if (!is.null(shape)) { 47 | filtered <- crop(x = filtered, y = shape) 48 | terra::plot(shape, col = "gold4", add = T, pch = 20, cex = cex) 49 | } 50 | for (i in 1:length(trait)) { 51 | Data <- values(filtered) 52 | vector <- Data[, colnames(Data) == trait[i]] 53 | mean1 <- mean(as.numeric(as.character(vector)), na.rm = T) 54 | sd1 <- sd(as.numeric(as.character(vector)), na.rm = T) 55 | print(paste("Filter ", i, ": cleaning data for the trait '", 56 | trait[i], "' (mean=", round(mean1, 2), ") using values between '", 57 | value[i], "' degrees of the standard deviation (sd=", 58 | round(sd1, 2), ").", sep = "")) 59 | sel <- abs(vector - mean1) < c(sd1 * value[i]) 60 | sel[is.na(sel)] <- FALSE 61 | title <- paste("Filter: \n", trait[i], " > ", round(c(mean1 - 62 | value[i] * sd1), 2), " and < ", round(c(mean1 + 63 | value[i] * sd1), 2), sep = "") 64 | filtered <- filtered[sel, ] 65 | if (!is.null(shape)) { 66 | terra::plot(shape, main = title) 67 | terra::plot(filtered, col = "gold4", pch = 20, add = T, 68 | cex = cex) 69 | } 70 | if (is.null(shape)) { 71 | terra::plot(filtered, col = "gold4", main = title, pch = 20, 72 | cex = cex) 73 | } 74 | } 75 | par(mfrow = c(1, 1)) 76 | return(filtered) 77 | } 78 | -------------------------------------------------------------------------------- /R/fct_filterField.R: -------------------------------------------------------------------------------- 1 | #' filterField 2 | #' 3 | #' @title Filter spatial vector data based on value 4 | #' 5 | #' @description This function filters spatial vector data based on trait value. 6 | #' 7 | #' @param field SpatVector. The field to be filtered. 8 | #' @param shape a specific area inside the field to be filtered. If shape=NULL, all field data will be used for filtering. 9 | #' @param trait a vector of the traits to be used as filter criteria. 10 | #' @param value threshold value to filter the trait data (must be numeric). 11 | #' @param cropAbove if TRUE all data above the 'value' will be retained. if FALSE all data below the 'value' will be retained. 12 | #' @param cex point size. Please check \code{help("points")}. 13 | #' 14 | #' @importFrom terra crop plot 15 | #' @importFrom graphics par 16 | #' @importFrom methods as is 17 | #' 18 | #' 19 | #' @return the filtered SpatVector. 20 | #' 21 | #' 22 | #' @export 23 | filterField = function (field, shape = NULL, trait = NULL, value = NULL, cropAbove = NULL, 24 | cex = 1) 25 | { 26 | Data <- values(field) 27 | if (is.null(trait)) { 28 | stop(paste("Choose one or more 'trait' for filtering in this list: ", 29 | paste(colnames(Data), collapse = ", "), ".", sep = "")) 30 | } 31 | if (!all(trait %in% colnames(Data))) { 32 | stop(paste("'trait' is not in the list: ", paste(colnames(Data), 33 | collapse = ", "), ".", sep = "")) 34 | } 35 | if (!all(is.numeric(value))) { 36 | stop(paste("Choose one numeric value as a treshold/crop for each 'trait' in this list: ", 37 | paste(trait, collapse = ", "), ".", sep = "")) 38 | } 39 | if (length(value) != length(trait)) { 40 | stop(paste("'value' must be the same length of 'trait': ", 41 | length(trait), ".", sep = "")) 42 | } 43 | if (!is.logical(cropAbove)) { 44 | stop("'cropAbove' must be logical(TRUE or FALSE)") 45 | } 46 | if (length(cropAbove) != length(trait)) { 47 | stop(paste("'cropAbove' must be TRUE or FALSE and with the same length of 'trait': ", 48 | length(trait), ".", sep = "")) 49 | } 50 | filtered <- field 51 | par(mfrow = c(1, length(trait) + 1)) 52 | terra::plot(field, col = "bisque3", main = "Original", pch = 20, 53 | cex = cex) 54 | if (!is.null(shape)) { 55 | filtered <- terra::crop(x = filtered, y = shape) 56 | terra::plot(shape, col = "gold4", add = T, pch = 20) 57 | } 58 | for (i in 1:length(trait)) { 59 | print(paste("Filter ", i, ": cleaning for the trait '", 60 | trait[i], "' using the value '", value[i], "' and cropAbove=", 61 | cropAbove[i], ".", sep = "")) 62 | Data <- values(filtered) 63 | vector <- Data[, colnames(Data) == trait[i]] 64 | if (value[i] > max(vector, na.rm = T) | value[i] < min(vector, 65 | na.rm = T)) { 66 | stop(paste("Choose a 'value' for filtering the trait '", 67 | trait, "' between ", min(vector, na.rm = T), 68 | " and ", max(vector, na.rm = T), ".", sep = "")) 69 | } 70 | if (cropAbove[i]) { 71 | sel <- vector > value[i] 72 | sel[is.na(sel)] <- FALSE 73 | title <- paste(" > ", value[i], sep = "") 74 | } 75 | if (!cropAbove[i]) { 76 | sel <- vector < value[i] 77 | sel[is.na(sel)] <- FALSE 78 | title <- paste(" < ", value[i], sep = "") 79 | } 80 | filtered <- filtered[sel, ] 81 | if (!is.null(shape)) { 82 | terra::plot(shape, main = paste("Filter: ", trait[i], title, 83 | sep = "")) 84 | terra::plot(filtered, col = "gold4", pch = 20, add = T, 85 | cex = cex) 86 | } 87 | if (is.null(shape)) { 88 | terra::plot(filtered, col = "gold4", main = paste("Filter: ", 89 | trait[i], title, sep = ""), pch = 20, cex = cex) 90 | } 91 | } 92 | par(mfrow = c(1, 1)) 93 | return(filtered) 94 | } 95 | -------------------------------------------------------------------------------- /tut_code.R: -------------------------------------------------------------------------------- 1 | rm(list=ls()) 2 | setwd(dirname(rstudioapi::getSourceEditorContext()$path)) 3 | # devtools::install_github("filipematias23/cleanRfield") 4 | 5 | ################### 6 | ### cleanRfield ### 7 | ################### 8 | 9 | library(cleanRfield) 10 | library(terra) 11 | 12 | ### Opening Sample Field 1 ### 13 | par(mfrow=c(1,2)) 14 | EX1<-vect("EX1/EX1.shp") 15 | plot(EX1, main="Data Point") 16 | 17 | EX1.Shape<-vect("EX1_boundary/EX1_boundary.shp") 18 | plot(EX1.Shape, main="Field Boundary") 19 | par(mfrow=c(1,1)) 20 | 21 | # "Use cursor to select 4 points around of polygon (1) in the plots window." 22 | EX1.C<-cropField(field = EX1, nPolygon = 1, nPoint = 4) 23 | 24 | plot(EX1.C$shape,main="Drawing Shape") 25 | 26 | # Using the shape drawn above to crop data: 27 | EX1.C<-cropField(field = EX1, shape = EX1.C$shape) 28 | 29 | # All data will be selected using the full boundary as shape: 30 | EX1.C1<-cropField(field = EX1, shape = EX1.Shape) 31 | 32 | #Open an extra plot window 33 | x11() 34 | # "Use cursor to select 4 points around of polygon (1) in the plots window." 35 | EX1.C<-cropField(field = EX1, nPolygon = 1, nPoint = 4) 36 | 37 | # Sampling 5%: 38 | EX1.S<-sampleField(field = EX1, size = 0.05) 39 | 40 | # Sampling 10% under a small shape: 41 | EX1.S<-sampleField(field = EX1,shape = EX1.C$shape, size = 0.1) 42 | 43 | # Sampling 10% under a full shape: 44 | EX1.S<-sampleField(field = EX1,shape = EX1.Shape, size = 0.1) 45 | 46 | # Check projection to observe 'LENGTHUNIT': 47 | crs(EX1) 48 | 49 | # Unprojected Data (non or NA): use resolution around 0.00008 to create a raster for "Dry_Yield": 50 | EX1.R<-rasterField(field = EX1, 51 | trait = c("Dry_Yield"), 52 | res = 0.00008) 53 | 54 | # Projected Data (e.g., +units=m or +units=us-ft): use resolution around 5 to 20 to create a raster for "Dry_Yield": 55 | EX1.R<-rasterField(field = EX1, 56 | trait = c("Dry_Yield"), 57 | res = .0002) 58 | 59 | # Making raster only for the small shape: 60 | EX1.R<-rasterField(field = EX1, 61 | shape = EX1.C$shape, 62 | trait = c("Dry_Yield"), 63 | res = 0.00008) # Attention: for projected data use res=20 (e.g., +units=m or +units=us-ft). 64 | 65 | # Multilayer raster for two or more traits: 66 | EX1.R<-rasterField(field = EX1, 67 | trait = c("Dry_Yield","Speed"), 68 | res = 0.00008) # Attention: for projected data use res=20 (e.g., +units=m or +units=us-ft). 69 | 70 | # Different raster color visualizations: 71 | library(RColorBrewer) 72 | par(mfrow=c(2,3)) 73 | plot(EX1.R$Dry_Yield) 74 | plot(EX1.R$Dry_Yield,col = heat.colors(10)) 75 | plot(EX1.R$Dry_Yield,col = topo.colors(10)) 76 | plot(EX1.R$Dry_Yield,col = brewer.pal(11, "RdYlGn")) 77 | plot(EX1.R$Dry_Yield,col = brewer.pal(9, "BuGn")) 78 | plot(EX1.R$Dry_Yield,col = brewer.pal(9, "Greens")) 79 | par(mfrow=c(1,1)) 80 | 81 | # Making shapefile of field boundary 82 | EX1.P<-boundaryField(field = EX1.R$Dry_Yield, tolerance = 0.0004) # Yield data did not capture borders of field 83 | EX1.P<-boundaryField(field = EX1.R$Speed) # Speed data has defined field borders, we use default tolerance 84 | 85 | EX1.P<-boundaryField(field = EX1, draw = TRUE) 86 | 87 | # Upper field: 88 | EX1.P1<-boundaryField(field = EX1, draw = T) # Manually 89 | 90 | # Middle field: 91 | EX1.P2<-boundaryField(field = EX1, draw = T) 92 | 93 | # Lower field: 94 | EX1.P3<-boundaryField(field = EX1, draw = T) 95 | 96 | # Combining field on the same shapefile: 97 | EX1.P<-rbind(EX1.P1,EX1.P2,EX1.P3) 98 | plot(EX1.P) 99 | 100 | # Check projection to observe 'LENGTHUNIT': 101 | crs(EX1) 102 | 103 | # Unprojected Data (e.g., non or NA): buffer of -15 meters: 104 | EX1.B<-bufferField(shape = EX1.Shape,value = -15) 105 | 106 | # Projected Data (e.g., +units=m or +units=us-ft): buffer of -50 meters: 107 | EX1.B<-bufferField(shape = EX1.Shape, value = -50) 108 | 109 | # Buffer of (Unprojected Data) and -5 (Projected Data): 110 | EX1.B<-bufferField(shape = EX1.Shape, 111 | field = EX1, 112 | value = -15) # Attention: for projected data use 'value=-5' (e.g., +units=m or +units=us-ft). 113 | 114 | par(mfrow=c(1,2)) 115 | hist(EX1$Dry_Yield) 116 | hist(EX1$Speed) 117 | par(mfrow=c(1,1)) 118 | 119 | # Filtering data for Dry_Yield>50 and Dry_Yield<70: 120 | EX1.F<-filterField(field = EX1, 121 | trait = c("Dry_Yield","Dry_Yield"), 122 | value = c(50,70), 123 | cropAbove = c(T,F)) 124 | 125 | # Filtering data for Dry_Yield>50 and Dry_Yield<70 (only for the data on the small shapefile): 126 | 127 | EX1.F<-filterField(field = EX1, 128 | shape = EX1.C$shape, 129 | trait = c("Dry_Yield","Dry_Yield"), 130 | value = c(50,70), 131 | cropAbove = c(T,F)) 132 | 133 | # Filtering data for Dry_Yield>70 and Speed<5 (using the buffer shapefile): 134 | 135 | EX1.F<-filterField(field = EX1, 136 | shape = EX1.B$newShape, 137 | trait = c("Dry_Yield","Speed"), 138 | value = c(70,5), 139 | cropAbove = c(T,F)) 140 | 141 | # Filtering data for Dry_Yield sd<0.2: 142 | 143 | EX1.SD<-sdField(field = EX1, 144 | trait = c("Dry_Yield"), 145 | value = 0.2) 146 | 147 | # Filtering data for Dry_Yield sd<0.5 and Dry_Yield sd<0.2: 148 | 149 | EX1.SD<-sdField(field = EX1, 150 | trait = c("Dry_Yield","Dry_Yield"), 151 | value = c(0.5,0.2)) 152 | 153 | # Filtering data for Dry_Yield sd<0.5 and Speed sd<0.2 (only for the data on the small shapefile): 154 | 155 | EX1.SD<-sdField(field = EX1, 156 | shape = EX1.C$shape, 157 | trait = c("Dry_Yield","Speed"), 158 | value = c(0.5,0.2)) 159 | 160 | # Filtering data for Dry_Yield sd<0.5 and Speed sd<0.2 (using the buffer shapefile): 161 | 162 | EX1.SD<-sdField(field = EX1, 163 | shape = EX1.B$newShape, 164 | trait = c("Dry_Yield","Speed"), 165 | value = c(0.5,0.2)) 166 | 167 | ################ 168 | ### Parallel ### 169 | ################ 170 | 171 | # Required packages 172 | library(parallel) 173 | library(foreach) 174 | library(doParallel) 175 | 176 | # Files names (folder directory: "./field/" and "./boundary/") 177 | field<-unique(do.call(rbind,strsplit(list.files("./field/"),split = "[.]"))[,1]) 178 | boundary<-unique(do.call(rbind,strsplit(list.files("./boundary/"),split = "[.]"))[,1]) 179 | 180 | # General filter information: 181 | buffer=-50 # Boundary buffer of 50 feet 182 | trait = c("Dry_Yield","Speed") # Filtered traits 183 | filter.value = c(50,7) # cropping filter values 184 | cropAbove = c(T,T) # All values above the filter.value 185 | sd.value = c(1,1) # All values between sd=1 186 | 187 | # Number of cores 188 | n.core<-3 189 | 190 | # Starting parallel 191 | cl <- makeCluster(n.core, output = "") 192 | registerDoParallel(cl) 193 | Filtered_Field <-foreach(i = 1:length(field), 194 | .packages = c("terra","cleanRfield")) %dopar% { 195 | 196 | # Uploading data and boundary 197 | F.ex<-vect(paste("./field/",field[i],".shp",sep="")) 198 | B.ex<-vect(paste("./boundary/",boundary[i],".shp",sep="")) 199 | 200 | # Filtering the borders by buffering the boundary shape file: 201 | B.ex<-bufferField(shape = B.ex,value = buffer) 202 | 203 | # Filtering data based on observed traits values: 204 | F.ex<-filterField(field = F.ex, 205 | shape = B.ex, 206 | trait = trait, 207 | value = filter.value, 208 | cropAbove = cropAbove) 209 | 210 | # Filtering data based on standard deviation values: 211 | F.ex<-sdField(field = F.ex, 212 | shape = B.ex, 213 | trait = trait, 214 | value = sd.value) 215 | 216 | # New filtered data and boundary files: 217 | return(list(NewField=wrap(F.ex), NewBoundary=wrap(B.ex))) 218 | } 219 | 220 | stopCluster(cl) 221 | names(Filtered_Field)<-field 222 | 223 | # Output 224 | Filtered_Field = lapply(unlist(Filtered_Field), unwrap) 225 | 226 | # New filtered - EX2_center 227 | plot(Filtered_Field$EX2_center.NewBoundary, main="EX2_center") 228 | plot(Filtered_Field$EX2_center.NewField, add=T, col="gold4",pch=20,cex=0.5) 229 | 230 | 231 | # New filtered - EX2_north 232 | plot(Filtered_Field$EX2_north.NewBoundary, main="EX2_north") 233 | plot(Filtered_Field$EX2_north.NewField, add=T, col="gold4",pch=20,cex=2) 234 | 235 | 236 | # New filtered - EX2_south 237 | plot(Filtered_Field$EX2_south.NewBoundary, main="EX2_south") 238 | plot(Filtered_Field$EX2_south.NewField, add=T, col="gold4",pch=20,cex=1) 239 | 240 | 241 | # Combined new data: 242 | NewField<-rbind(Filtered_Field$EX2_center.NewField, 243 | Filtered_Field$EX2_north.NewField, 244 | Filtered_Field$EX2_south.NewField) 245 | 246 | # Giving names to each field: 247 | Filtered_Field$EX2_center.NewBoundary$ID<-field[1] 248 | Filtered_Field$EX2_north.NewBoundary$ID<-field[2] 249 | Filtered_Field$EX2_south.NewBoundary$ID<-field[3] 250 | 251 | # Combining field on the same shape file: 252 | NewBoundary<-rbind(Filtered_Field$EX2_center.NewBoundary, 253 | Filtered_Field$EX2_north.NewBoundary, 254 | Filtered_Field$EX2_south.NewBoundary) 255 | 256 | plot(NewBoundary, main="EX2_full") 257 | plot(NewField, add=T, col="gold4",pch=20,cex=0.5) 258 | 259 | # Make a very basic plot where brighter colors denote higher yield 260 | terra::plot(EX1, "Dry_Yield") 261 | 262 | #Adjusting breaks changes the number of categories in the legend 263 | terra::plot(EX1, "Dry_Yield", breaks=6) 264 | 265 | #convert the object EX1 into an sf object named EX1sf 266 | library(sf) 267 | EX1sf<-st_as_sf(EX1) 268 | 269 | #plot the data using geom_sf and the ggplot2 default color gradient 270 | library(ggplot2) 271 | ggplot()+ 272 | geom_sf(data=EX1sf, aes(color= Dry_Yield))+ 273 | theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) 274 | 275 | #or make a figure using fewer of the ggplot2 display defaults 276 | EX1.F10<-filterField(field = EX1, #filtering with Dry_Yield>10 to create a different example for plotting data 277 | trait = "Dry_Yield", 278 | value = 10, 279 | cropAbove = T) 280 | EX1sf10<-st_as_sf(EX1.F10) #converting the object EX1.F10 into an sf object 281 | ggplot() + 282 | geom_sf(data = EX1sf10, aes(color = Dry_Yield), size = 0.01) + #made the individual points smaller 283 | scale_color_gradient(low = "yellow2", high = "green4") + #created a different color gradient 284 | ggtitle("Field EX1.F10 Filtered Yield") + #added a main figure title 285 | labs(color='Dry Yield (bu/acre)') + #changed legend title 286 | theme_void() #removed grid background from figure 287 | 288 | writeVector(EX1.B$newField, "EX1.newField.shp", filetype="ESRI Shapefile") 289 | EX1.newField <- vect("EX1.newField.shp") # Reading the saved data points. 290 | 291 | # reading in the .csv file 292 | DF<-read.csv("EX3.csv") 293 | colnames(DF) #checking that the latitude is the first column and longitude is the second column 294 | 295 | # creating the coordinates object using the latitude and longitude columns 296 | DF$xy <- lapply(c('Long','Lat'), c()) 297 | DF$xy = c(df$Long,df$Lat) 298 | xy <- DF[,c(1,2)] 299 | 300 | # creating a new spatial points data frame from the data in DF 301 | SpatialDF <- vect(DF, geom=c('Long','Lat'), crs = "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0") 302 | crs(SpatialDF) 303 | 304 | #### additional packages needed for interpolation & mapping #### 305 | library(gstat) # used to make the idw model 306 | library(sp) # used to prepare the raster grid with spsample function 307 | library(tmap) # used for visualization 308 | 309 | #### preparing the yield data #### 310 | EX1 <- vect("EX1/EX1.shp") # EX1.shp download link is in tutorial section 1 311 | EX1.Shape <- vect("EX1_boundary/EX1_boundary.shp") #EX1_boundary.shp download link is in tutorial section 1 312 | 313 | # filtering data to remove biologically unlikely soybean yield observations and NA values 314 | EX1.F <- filterField(field = EX1, 315 | trait = c("Dry_Yield","Dry_Yield"), 316 | value = c(10,100), 317 | cropAbove = c(T,F)) 318 | 319 | # transforming the filtered data so that it is a projected CRS 320 | EX1_merc <- spTransform(as_Spatial(st_as_sf(EX1.F)), CRS=CRS("+proj=merc +ellps=GRS80")) 321 | EX1_merc # looking at summary output to check projection 322 | 323 | #transforming the boundary too-- this will be used later for visualization 324 | EX1.Shape_merc <- spTransform(as_Spatial(st_as_sf(EX1.Shape)), CRS=CRS("+proj=merc +ellps=GRS80")) 325 | EX1.Shape_merc #looking at summary output to check projection 326 | 327 | #### preparing an empty grid #### 328 | G <- as.data.frame(spsample(EX1_merc,"regular", n=50000)) #n = total number of grid cells 329 | names(G) <- c("X", "Y") 330 | coordinates(G) <- c("X", "Y") 331 | gridded(G) <- TRUE # create SpatialPixel object 332 | fullgrid(G) <- TRUE # create SpatialGrid object 333 | proj4string(G) <- proj4string(EX1_merc) # using the projection from EX1_merc to project the grid G 334 | proj4string(G) # checking that G is projected 335 | 336 | #### running IDW using the yield data and empty grid #### 337 | Yield.idw <- gstat::idw(Dry_Yield ~ 1, EX1_merc, newdata=G, idp=2.0) 338 | 339 | #### visualizing IDW interpolation #### 340 | r.idw <- raster::raster(Yield.idw) # convert the IDW model to a RasterStack 341 | r.masked <- raster::mask(r.idw, EX1.Shape_merc) # mask the raster to the field boundary 342 | 343 | yieldmap.idw <- tm_shape(r.masked) + #make the map using functions from the tmap library 344 | tm_raster(n=10,palette = "YlGn", 345 | title="Dry Yield") + 346 | tm_legend(legend.outside=TRUE) 347 | yieldmap.idw #view the map 348 | 349 | #### additional packages needed for interpolation & mapping #### 350 | library(gstat) # used to make the idw model 351 | library(sf) 352 | library(sp) # used to prepare the raster grid with spsample function 353 | library(tmap) # used for visualization 354 | 355 | #### preparing the yield data #### 356 | EX1 <- vect("EX1/EX1.shp") # EX1.shp download link is in tutorial section 1 357 | EX1.Shape <- vect("EX1_boundary/EX1_boundary.shp") #EX1_boundary.shp download link is in tutorial section 1 358 | 359 | # filtering data to remove biologically unlikely soybean yield observations and NA values 360 | EX1.F <- filterField(field = EX1, 361 | trait = c("Dry_Yield","Dry_Yield"), 362 | value = c(10,100), 363 | cropAbove = c(T,F)) 364 | 365 | # transforming the filtered data so that it is a projected CRS 366 | EX1_merc <- spTransform(as_Spatial(st_as_sf(EX1.F)), CRS=CRS("+proj=merc +ellps=GRS80")) 367 | EX1_merc # looking at summary output to check projection 368 | 369 | #transforming the boundary too-- this will be used later for visualization 370 | EX1.Shape_merc <- spTransform(as_Spatial(st_as_sf(EX1.Shape)), CRS=CRS("+proj=merc +ellps=GRS80")) 371 | EX1.Shape_merc #looking at summary output to check projection 372 | 373 | #### make a variogram to assess spatial relationships between yield observations #### 374 | v_overall <- variogram(Dry_Yield~1, data = EX1_merc) 375 | plot(v_overall) # visually estimate sill, model shape, range, and nugget 376 | vmodel_overall <- vgm(psill=150, model="Sph", nugget=100, range=400) # estimate variogram model 377 | fittedmodel_overall <- fit.variogram(v_overall, model=vmodel_overall) # fit variogram model 378 | fittedmodel_overall #print the fitted model to see how it compares to your initial estimate 379 | plot(v_overall, model=fittedmodel_overall) 380 | 381 | 382 | # let's see if the spatial autocorrelation is the same in all directions-- is the data anisotrophic? 383 | gs_object <- gstat(formula=Dry_Yield~ 1, data=EX1_merc) 384 | v_directional <- variogram(gs_object, alpha=c(0,45,90,135)) 385 | vmodel_directional <- vgm(model='Sph' , anis=c(0, 0.5)) 386 | fittedmodel_directional <- fit.variogram(v_directional, model=vmodel_directional) 387 | plot(v_directional, model=fittedmodel_directional, as.table=TRUE) 388 | 389 | 390 | #### sample 20% of yield observations #### 391 | EX1_merc_10pct<-sampleField(field = EX1_merc, size = 0.2) 392 | 393 | #### update the empty grid and gstat object #### 394 | # prepare a similar, but smaller, empty grid than the IDW example code 395 | G <- as.data.frame(spsample(EX1_merc, "regular", n=10000)) 396 | names(G) <- c("X", "Y") 397 | coordinates(G) <- c("X", "Y") 398 | gridded(G) <- TRUE # Create SpatialPixel object 399 | fullgrid(G) <- TRUE # Create SpatialGrid object 400 | proj4string(G) <- proj4string(EX1_merc) 401 | proj4string(G) #checking that G is projected 402 | 403 | # now update the gstat object from before so that it includes the fitted 404 | # model, not the estimated model from earlier in the kriging workflow 405 | gs_object <- gstat(formula=Dry_Yield~ 1, 406 | data=as_Spatial(st_as_sf(EX1_merc_10pct)), model=fittedmodel_overall) 407 | 408 | #### run the kriging procedure using the gstat object and empty grid #### 409 | kriged_surface <- predict(gs_object, model=fittedmodel_overall, newdata=G) 410 | 411 | summary(kriged_surface) 412 | 413 | 414 | #### visualizing kriged map #### 415 | kriged_raster <- raster::raster(kriged_surface) 416 | kriged_masked <- raster::mask(kriged_raster, EX1.Shape_merc) 417 | 418 | tm_shape(kriged_masked) + 419 | tm_raster(n=10,palette = "YlGn", 420 | title="Dry Yield") + 421 | tm_legend(legend.outside=TRUE) 422 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ## [cleanRfield](https://github.com/filipematias23/cleanRfield): A tool for cleaning and filtering data spatial points from crop yield maps in [R](https://www.r-project.org). 3 | 4 | > This package is a compilation of functions to clean and filter observations from yield monitors or other agricultural spatial point data. Yield monitors are prone to error, and filtering the observations or removing observations from near field boundaries can improve estimates of whole-field yield, combine speed, grain moisture, or other parameters of interest. In this package, users can easily select filters for one or more traits and prepare a smaller dataset to make decisions. 5 | 6 | > This tutorial assumes that readers have a basic understanding of spatial data, including projections and coordinate reference systems. If you need a refresher on this topic, we recommend reading [this blog post for deciding between projected and unprojected data](https://spatiallychallenged.com/2018/11/01/selecting-a-projection-for-spatial-analysis/) and [this post for understanding the basics of coordinate reference systems](https://spatiallychallenged.com/2018/11/05/epsg-numbers-and-coordinate-reference-systems/). 7 | 8 |

9 | 10 |

11 | 12 |