Re: [R-sig-Geo] ordering points into a line

2024-06-06 Thread Ben Tupper
Interesting - thanks for passing that along.

On Thu, Jun 6, 2024 at 6:32 AM Adrian Baddeley
 wrote:
>
> Ben Tupper writes:
>
> > This dataset provides an interesting spatial puzzle because the points
> > for a specific wall on a given date are not ordered.  Assuming that
> > the points could be ordered into LINESTRING, the problem is how to do it.
>
> This is a special case of the Travelling Salesman Problem
> and you could use the R package 'TSP' for example..
>
> Adrian Baddeley
>
>
>
>
>
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] ordering points into a line

2024-06-05 Thread Ben Tupper
You make it look so easy!  That is just what I was trying to noodle
out.  I need to spend more time digging into the
[s2](https://r-spatial.github.io/s2/index.html) package.  Thank you!


On Wed, Jun 5, 2024 at 1:09 PM Dewey Dunnington  wrote:
>
> Hi Ben,
>
> I had a bit of fun with this [1]...the act of following a shortest path
> and finding the endpoints are sort of related (in that if you follow the
> shortest path setting a maximum distance threshold, eventually you will
> fail to find any more points, and you've found (maybe) and endpoint!).
>
> I hope this is helpful!
>
> Cheers,
>
> -dewey
>
> [1] https://gist.github.com/paleolimbot/0be47836de5008f308959923dac02c5b
>
> On 2024-06-05 13:20, Ben Tupper wrote:
> > Hello,
> >
> > NOAA's Ocean Prediction Center (https://ocean.weather.gov/) serves the
> > US Navy's almost-daily estimate of the locations of the north and
> > south walls of the Gulf Stream in the North Atlantic
> > (https://ocean.weather.gov/gulf_stream_latest.txt). The also serve an
> > archive via a FTP server
> > (https://ftp.opc.ncep.noaa.gov/grids/experimental/GStream) for
> > downloads by year.  The dataset provides manually estimated of
> > locations along the so-called north and south walls of the Gulf
> > Stream, although there is ongoing research and debate about the best
> > way to define the Gulf Stream. My colleagues and I have been slowly
> > pulling together a small package to make working with this data easier
> > (https://github.com/BigelowLab/gstream).
> >
> > This dataset provides an interesting spatial puzzle because the points
> > for a specific wall on a given date are not ordered.  Assuming that
> > the points could be ordered into LINESTRING, the problem is how to do
> > it.
> >
> > We probably can use sfnetworks package
> > (https://luukvdmeer.github.io/sfnetworks/) extensive tools to follow a
> > shortest path... but first one of the two endpoints must be found.
> > Eeek! How does one do that programmatically?  The plot attached shows
> > the points for the north wall on 2020-12-19.  Also shown are the first
> > and last points in the record which are clearly not the endpoints of a
> > path we might assemble from the points.
> >
> >  START
> > suppressPackageStartupMessages({
> >   library(sf)
> >   library(readr)
> >   library(dplyr)
> > })
> >
> >
> > file =
> > "https://raw.githubusercontent.com/BigelowLab/gstream/main/inst/examples/2020-12-19-north.csv;
> > x = readr::read_csv(file, col_types = "nn") |>
> >   sf::st_as_sf(coords = c("X", "Y"), crs = 4326) |>
> >   sf::st_as_sf()
> >
> >
> > p = sf::st_cast(dplyr::select(x, attr(x, "sf_column")), "POINT")
> > plot(sf::st_geometry(x), type = "b", axes = TRUE, reset = FALSE)
> > plot(dplyr::slice(p,1), col = "orange", add = TRUE, pch = 2, cex = 1.5)
> > plot(dplyr::slice(p,nrow(x)), col = "orange", add = TRUE, pch = 6, cex
> > = 1.5)
> > ### END
> >
> > --
> >
> > Ben Tupper he/him
> >
> > Research Associate
> >
> > Bigelow Laboratory for Ocean Sciences
> >
> > –––
> >
> > E  btup...@bigelow.org
> >
> > O  207-315-2567
> >
> > –––
> >
> > Bold Science for Our Blue Planet  |  BIGELOW.ORG
> >
> > 60 BIGELOW DRIVE  |  EAST BOOTHBAY, MAINE 04544 USA
> >
> > ___
> > R-sig-Geo mailing list
> > R-sig-Geo@r-project.org
> > https://stat.ethz.ch/mailman/listinfo/r-sig-geo

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


[R-sig-Geo] ordering points into a line

2024-06-05 Thread Ben Tupper
Hello,

NOAA's Ocean Prediction Center (https://ocean.weather.gov/) serves the
US Navy's almost-daily estimate of the locations of the north and
south walls of the Gulf Stream in the North Atlantic
(https://ocean.weather.gov/gulf_stream_latest.txt). The also serve an
archive via a FTP server
(https://ftp.opc.ncep.noaa.gov/grids/experimental/GStream) for
downloads by year.  The dataset provides manually estimated of
locations along the so-called north and south walls of the Gulf
Stream, although there is ongoing research and debate about the best
way to define the Gulf Stream. My colleagues and I have been slowly
pulling together a small package to make working with this data easier
(https://github.com/BigelowLab/gstream).

This dataset provides an interesting spatial puzzle because the points
for a specific wall on a given date are not ordered.  Assuming that
the points could be ordered into LINESTRING, the problem is how to do
it.

We probably can use sfnetworks package
(https://luukvdmeer.github.io/sfnetworks/) extensive tools to follow a
shortest path... but first one of the two endpoints must be found.
Eeek! How does one do that programmatically?  The plot attached shows
the points for the north wall on 2020-12-19.  Also shown are the first
and last points in the record which are clearly not the endpoints of a
path we might assemble from the points.

 START
suppressPackageStartupMessages({
  library(sf)
  library(readr)
  library(dplyr)
})


file = 
"https://raw.githubusercontent.com/BigelowLab/gstream/main/inst/examples/2020-12-19-north.csv;
x = readr::read_csv(file, col_types = "nn") |>
  sf::st_as_sf(coords = c("X", "Y"), crs = 4326) |>
  sf::st_as_sf()


p = sf::st_cast(dplyr::select(x, attr(x, "sf_column")), "POINT")
plot(sf::st_geometry(x), type = "b", axes = TRUE, reset = FALSE)
plot(dplyr::slice(p,1), col = "orange", add = TRUE, pch = 2, cex = 1.5)
plot(dplyr::slice(p,nrow(x)), col = "orange", add = TRUE, pch = 6, cex = 1.5)
### END

-- 

Ben Tupper he/him

Research Associate

Bigelow Laboratory for Ocean Sciences

–––

E  btup...@bigelow.org

O  207-315-2567

–––

Bold Science for Our Blue Planet  |  BIGELOW.ORG

60 BIGELOW DRIVE  |  EAST BOOTHBAY, MAINE 04544 USA

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Recommendations for wildfire risk analysis (spatially explicit)

2024-01-21 Thread Ben Tupper
Hi,

Perhaps this might be a good place to start?

https://esajournals.onlinelibrary.wiley.com/doi/10.1002/eap.1898  The
authors state that the work was done primarily in R.

Cheers,
Ben


On Sat, Jan 20, 2024 at 9:43 AM Manuel Spínola  wrote:
>
> Dear list members,
>
> I am looking for suggestions for R packages or an approach using R for
> wildfire risk analysis.
>
> Manuel
>
> --
> *Manuel Spínola, Ph.D.*
> Instituto Internacional en Conservación y Manejo de Vida Silvestre
> Universidad Nacional
> Apartado 1350-3000
> Heredia
> COSTA RICA
> mspin...@una.cr 
> mspinol...@gmail.com
> Teléfono: (506) 8706 - 4662
> Sitio web institucional: ICOMVIS
> 
> Sitio web personal: Sitio personal 
> Blog sobre Ciencia de Datos: Blog de Ciencia de Datos
> 
>
> [[alternative HTML version deleted]]
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Counting points in cells and ploting only cells containing points

2023-11-28 Thread Ben Tupper
Oh, that's an interesting approach; I haven't seen `count()` used like that
- nice!.

Here's an alternative that uses stars as a raster container, and the
`st_cells()` function to determine which cell each point belongs to.

### START
suppressPackageStartupMessages({
  library(stars)
  library(sf)
  library(dplyr)
})

#' Given cell indices, convert to col-row addresses
#' @export
#' @param x stars object
#' @param cells num, cell addresses
#' @return matrix of [col, row]
colrow_from_cells <- function(x, cells){
  d = dim(x)
  if (any(cells > prod(d))) stop("cell indices must <= nrow(x) * ncol(x)")
  col = ((cells-1) %% d[1])  + 1
  row = floor((cells - 1) / d[1]) + 1
  cbind(col, row)
}

R = system.file("tif/olinda_dem_utm25s.tif", package = "stars") |>
  stars::read_stars()


set.seed(1345)
pts = sf::st_bbox(R) |>
  sf::st_as_sfc() |>
  sf::st_sample(1) |>
  sf::st_as_sf() |>
  sf::st_set_geometry("geometry")
index = stars::st_cells(R, pts)
xy = colrow_from_cells(R, index)

# augment the pts with index, row and column
# group by index, get the count per group
pts = dplyr::mutate(pts,
index = index,
row = xy[,1],
col = xy[,2]) |>
  sf::st_drop_geometry() |>
  dplyr::group_by(index) |>
  dplyr::group_map(
function(tbl, key){
  dplyr::slice(tbl, 1) |>
dplyr::mutate(n = nrow(tbl))
}, .keep = TRUE) |>
  dplyr::bind_rows()


# make a "blank" copy of the raster, assign the counts to each cell
C = R*0
names(C) = "point count"
C[[1]][pts$index] <- pts$n
plot(C, axes = TRUE)
### END


On Wed, Nov 22, 2023 at 7:00 AM Dexter Locke  wrote:

> Here is one approach. Kind of a silly example with just one grid cell, but
> would work with more polygons and more points.
>
>
> library(sf)
> library(tidyverse)
>
> # make some points data
> # modified example from
> # https://r-spatial.github.io/sf/reference/geos_binary_pred.html
> (pts <-
> st_sfc(st_point(c(.5,.5)), st_point(c(1.5, 1.5)), st_point(c(2.5,
> 2.5))) |>
> st_as_sf()|>
> rowid_to_column(var = 'pts_id'))
>
> (pol <-
> st_polygon(list(rbind(c(0,0), c(2,0), c(2,2), c(0,2), c(0,0 |>
> st_sfc() |>
> st_as_sf()|>
> rowid_to_column(var = 'pol_id')
>   )
>
> # look at the data, crude 'map'
> plot(pts); plot(pol, add = TRUE) # take a look
>
> # perform the intersection
> pts_pol_int <-
>   pts |>
>   st_intersection(pol) # only going to retain the overlaps (drops
> non-intersecting elements)
>
> # count the overlaps
> cont_pts_pol_int <-
>   pts_pol_int |>
>   st_drop_geometry() |> # pulls out the data frame (or tibble)
>   group_by(pol_id) |>
>   count()
>
> cont_pts_pol_int # could be joined back to pol
>
> HTH, DHL
>
>
> On Wed, Nov 22, 2023 at 6:39 AM MIGUEL GOMEZ DE ANTONIO 
> wrote:
>
> > Dear community,
> >
> > I want to plot only the cells of a grid that contains points.
> >
> > I have a set of points (of class SpatialPointsDataFrame) and a grid (of
> > class SpatialPolygonDataFrame).
> >
> > I am interested in ploting the set of cells of the grid that contains
> > points:
> >
> > 1.   Count how many points fall in each cell of the grid.
> >
> > 2.   Plot only the cells that contains points.
> >
> > I tried:
> >
> > library(sf)
> >
> > Points.sf=st_as_sf(points)
> >
> > Grid.sf=st_as_sf(grid)
> >
> > A=intersects(grid.sf, points.sf)
> >
> > apply(A,1,any)
> >
> > There I get the cells that contains points but:
> >
> > 1. How can I count how many points fall in each cell
> >
> > 2. How could I plot the set of cells that contains points?
> >
> >
> > Thank you very much for your help,
> >
> >
> > Miguel Gómez de Antonio
> > Profesor Titular de Universidad
> > Dpto. Economía Aplicada, Pública y Política
> > Universidad Complutense de Madrid
> >
> > [[alternative HTML version deleted]]
> >
> > ___
> > R-sig-Geo mailing list
> > R-sig-Geo@r-project.org
> > https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> >
>
> [[alternative HTML version deleted]]
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Mapping census tracts with leaflet(): "sf layer has inconsistent datum" error

2023-05-31 Thread Ben Tupper
Hi,

This is a great place to ask - and nice reproducible code!

You have a two issues as far as I can see.  First it seems you have dropped
the "4" in "WGS84".  And second you want to transform rw_pop, not the
output of leaflet().  The following works for me.

## Start
library(tidyverse)
library(tidycensus)
library(leaflet)
library(sf)

rw_blocks <- c(3000, 3001, 3002, 3005, 3006, 3007, 3008, 3009, 3010, 3011)

rw_pop <- get_decennial(
  geography = "block",
  variables = "P1_001N",
  year = 2020,
  state = "MD",
  county = "Baltimore city",
  geometry = TRUE
) %>%
  filter(substr(GEOID, 6, 11) == "271101" &
   substr(GEOID, 12, 15) %in% rw_blocks
  ) ## %>% st_transform('+proj=longlat +datum=WGS8')

(rw_pop_map <- rw_pop %>%
st_transform('+proj=longlat +datum=WGS84') %>%
leaflet() %>%
fitBounds(-76.616, 39.352, -76.610, 39.346) %>%
addTiles() %>%
addPolygons()
)
## End

On Wed, May 31, 2023 at 4:03 PM Kevin Zembower via R-sig-Geo <
r-sig-geo@r-project.org> wrote:

> Hello, all. Newbie to sf, tidycensus and the tidyverse here.
>
> First off, is this the appropriate list to ask this question? If not,
> let me know and I'll go away.
>
> I'm trying to map census blocks for my neighborhood to a base map. I'm
> using tidycensus to get the geometry of the census blocks, and leaflet
> to map them to the OSM base maps. Mostly, this is going really well, and
> I'm very pleased with the speed of development (I just started this
> morning) and results.
>
> However, I get this error:
>
>   Warning message:
> sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
> Need '+proj=longlat +datum=WGS84'
>
> I think I need to use st_transform, but can't get it to work.
>
> Here's a reproducible example, with some commented out lines of what
> I've tried:
>
> ## Reproducible example:
> library(tidyverse)
> library(tidycensus)
> library(leaflet)
> library(sf)
>
> rw_blocks <- c(3000, 3001, 3002, 3005, 3006, 3007, 3008, 3009, 3010, 3011)
>
> rw_pop <- get_decennial(
>  geography = "block",
>  variables = "P1_001N",
>  year = 2020,
>  state = "MD",
>  county = "Baltimore city",
>  geometry = TRUE
> ) %>%
>  filter(substr(GEOID, 6, 11) == "271101" &
> substr(GEOID, 12, 15) %in% rw_blocks
> ) ## %>% st_transform('+proj=longlat +datum=WGS8')
>
> (rw_pop_map <- rw_pop %>%
>  leaflet() %>%
>   ## st_transform('+proj=longlat +datum=WGS8') %>%
>  fitBounds(-76.616, 39.352, -76.610, 39.346) %>%
>  addTiles() %>%
>  addPolygons()
>  )
> ## Error occurs when executing above block
>
> Can anyone offer me a hint as to how to resolve this error?
>
> Thanks so much for any advice and guidance.
>
> -Kevin
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Combine two polygons

2023-04-28 Thread Ben Tupper
Hi Milu,

If you want to combine just a few of the thousands of features in
world then you will have to manage them individually.  Essentially
extract the subset to be combined, do the combination steps, and then
add them back to the world.  I am very not familiar with GADM and I
only have version 4.1, but all of the attributes appear to be
character type, which raises the question about what you want
aggregate() to do - it can't take the mean of a character attribute.
In the example below I show how you might take just the first value of
each attribute.  While this combining is possible, it doesn't mean
that you will have "correct" attributes with your new single feature.
I guess you'll have to figure out what you really want to do with
that.

### start here
library(sf)
library(dplyr)
# a function called by aggregate() for each attribute
first_item = function(x){
  x[[1]]
}
# read in the database downlaoded from https://gadm.org/data.html
world = read_sf("~/Downloads/gadm_410.gpkg")
# find the Cypriot features (we'll use this twice)
ix = grepl("Cyp", world$NAME_0, fixed = TRUE)
# pull them out of world
Cyp_features = dplyr::filter(world, ix)
# aggregate - which works for the geometry but is wrong in terms of
handling the attributes
Cyp_union = aggregate(Cyp_features,
  sf::st_union(Cyp_features),
  first_item)
# bind the world (less Cypriot features) with the combined Cypriot aggregation
new_world = dplyr::bind_rows(dplyr::filter(world, !ix), Cyp_union)
### end here


Does that help?

Ben


On Fri, Apr 28, 2023 at 8:28 AM Roger Bivand  wrote:
>
> Briefly, is sf::aggregate() what you are looking for? Or terra::aggregate() 
> if you read with terra::vect()?
>
> ---
> Roger Bivand
> Emeritus Professor
> Department of Economics
> Norwegian School of Economics, Bergen, Norway
>
> 
> Fra: Miluji Sb 
> Sendt: fredag 28. april 2023, 14:18
> Til: Roger Bivand 
> Kopi: Michael Sumner ; R-sig-geo mailing list 
> 
> Emne: Re: [R-sig-Geo] Combine two polygons
>
> Thank you for your replies. I think I am misunderstanding something. I have 
> read the shapefile using sf. I would like to combine polygons for Cyprus and 
> Northern Cyprus only within the world shapefile and keep all the other 
> polygons as they are.
>
> world <- sf::st_read(dsn = "~/gadm36_levels_shp", layer = "gadm36_0")
>
> Is something like the following correct? I was thinking of generating a group 
> variable which is unique to all the countries except Cyprus and Northern 
> Cyprus. I a probably making this too complicated.
>
> world %>%
>   group_by(group) %>%
>   summarise(geometry = sf::st_union(geometry)) %>%
>   ungroup()
>
> Thank you again.
>
> Best regards,
>
> Milu
>
> On Fri, Apr 28, 2023 at 8:56 AM Roger Bivand 
> mailto:roger.biv...@nhh.no>> wrote:
> On Fri, 28 Apr 2023, Michael Sumner wrote:
>
> > fwiw, a method with geodata/terra
> >
> > cyp <- geodata::gadm(country = c("CYP", "XNC"), path = tempdir(), version =
> > "3.6")
> >
> > terra::aggregate(cyp)
> >
>
> and as per
> https://github.com/r-spatial/evolution/blob/main/pkgapi_230305_refs.csv.
>
> > see ?terra::writeVector to write it out
> >
> > (rgdal is very old and you should abandon it, it will be removed from
> > support by the end of this year)
>
> Thank you! Yes, sp will by default switch to using sf in place of rgdal
> for creating "CRS" objects, and under sp::spTransform in June, and all
> three retiring packages rgdal, rgeos, and maptools will be gone by October
> 2023. An sp release will appear in May with a transition guide.
>
> It seems that terra does not have an object corresponding to sp's "CRS" or
> sf's "crs". As far as I can see, one needs to create an empty
> SpatVector/SpatRaster object and assign a CRS, coerce to "Spatial", and
> extract its slot. If this makes sense, sp could use terra (and
> raster, needed for coercion) rather than sf where workflows did not
> otherwise use sf. Very grateful for input here or
> https://github.com/r-spatial/evolution/issues.
>
> Roger
>
> >
> >
> > (just as an aside, we can't hit the geodata vector urls directly with gdal
> > as we can with the rasters, as they are in an R specific format)
> >
> > Cheers, Mike
> >
> >
> > On Fri, Apr 28, 2023 at 10:52 AM Ben Tupper 
> > mailto:btup...@bigelow.org>> wrote:
> >
> >> Hi,
> >>
> >> You might try st_union() from the sf package
> >> https://r-spatial.github.io/sf/articles/sf3.html#geometrical-operat

Re: [R-sig-Geo] Combine two polygons

2023-04-27 Thread Ben Tupper
Hi,

You might try st_union() from the sf package
https://r-spatial.github.io/sf/articles/sf3.html#geometrical-operations



On Thu, Apr 27, 2023 at 5:37 PM Miluji Sb  wrote:

> Dear all,
>
> I am using the country-level shapefile from GADM. I would like to merge
> Cyprus and North Cyprus into one polygon. Is this possible? I am using
> rgdal to read the shapefile, subset, and then rewrite it. Any help will be
> highly appreciated.
>
> ##
> world <- readOGR("~/gadm36_levels_shp", layer = "gadm36_0")
>
> Best regards,
>
> Milu
>
> [[alternative HTML version deleted]]
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] r-sig-geo@r-project.org

2022-06-30 Thread Ben Tupper
Hi,

Hmmm... I think I can see what you are trying, but the mailing list
mangles HTML messages (switch your email to client to plain text mode
for this list).  Mifght you share what you get when you run,

dput(head(base))

in R?  That way each of us would have a small sample of your data.
And also resend the code to the list in plain text so we don't have to
to yoga moves to read the code?

Best wishes,
Ben


On Thu, Jun 30, 2022 at 9:30 AM David Romero  wrote:
>
> Hello,
> How can I construct an sf polyline object directly in sf? I have a data
> frame with 3 pairs of coordinates and need for each row a 2 segment line.
>
> I did it with sp but would like to migrate to sf:
>
> base$ID<-seq(1,nrow(base),1)
> base_lines <- apply(base,1,function(x){
>   points <- data.frame(lng=as.numeric(c(x["LONG1"],x["LONG2"],x["LONG3"])),
>
>  lat=as.numeric(c(x["LAT1"],x["LAT2"],x["LAT3"])),stringsAsFactors = F)
>   coordinates(points) <- c("lng","lat")
>   Lines(Line(points),ID=as.numeric(x["ID"]))})
> row.names(base) <- base$ID
> base_lines <- SpatialLinesDataFrame(SpatialLines(base_lines),base)
> sflines<-st_as_sf(base_lines)
>
> [[alternative HTML version deleted]]
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



-- 
Ben Tupper (he/him)
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] A leaflet question

2022-06-01 Thread Ben Tupper
Hmmm.  Are you looking to see which polygon the user clicks within?  If so,
perhaps look at sf::st_contains().  If that would do the trick then you
could skip casting `tarrant` to sp (leave it as sf object).  Then cast the
contents of click to to sf POINT using sf::st_as_sf().

On Wed, Jun 1, 2022 at 2:22 PM Erin Hodgess  wrote:

> Thank you so much!
>
> Here is the error that I get from nearPoints:
> nearPoints requires a click/hover/double-click object with x and y values.
>
> The "click" from the leaflet does not have the same components as the
> "click" from a regular plot.
>
> Erin Hodgess, PhD
> mailto: erinm.hodg...@gmail.com
>
>
> On Wed, Jun 1, 2022 at 2:16 PM Ben Tupper  wrote:
>
>> Hi Erin,
>>
>> I think it has to do with the naming convention.  If your map object is
>> called "plot", then you should expect the input to have the name
>> "plot_click" which you can access with `input$plot_click` You have looked
>> for input$plot_marker_click which hasn't been defined.
>>
>> I'm not sure why nearPoints() throws an error in this case.
>>
>>
>> ```
>> library(tigris)
>> library(leaflet)
>> library(sf)
>> options(tigris_use_cache = TRUE)
>> #Getting the data
>> tarrant <- tracts(state="TX",county="Tarrant",cb=TRUE)
>> tarrant_sp <- as(tarrant,"Spatial")
>>
>> #Set up ui
>> ui <- fluidPage(
>>   leafletOutput("plot"),
>>   tableOutput("data")
>> )
>> #Set up server
>> server <- function(input, output, session) {
>>   #Draw map
>>   output$plot <- renderLeaflet({
>> leaflet(tarrant_sp) %>% addTiles() %>%
>>   addPolygons(label=~TRACTCE)
>>   })
>>   #allegedly grab market clicks
>>   output$data <- renderTable({
>> click <- input$plot_click
>> cat("click class = ", class(click), "\n")
>> cat(str(click), "\n")
>> print(nearPoints(tarrant_sp, click))
>>   })
>> }
>> shinyApp(ui,server)
>> ```
>>
>> On Wed, Jun 1, 2022 at 10:15 AM Erin Hodgess 
>> wrote:
>>
>>> Thank you for your kind response.
>>>
>>> Here is my code:
>>>
>>> library(tigris)
>>> library(leaflet)
>>> library(sf)
>>>
>>> #Getting the data
>>> tarrant <- tracts(state="TX",county="Tarrant",cb=TRUE)
>>> tarrant_sp <- as(tarrant,"Spatial")
>>>
>>> #Set up ui
>>> ui <- fluidPage(
>>>   leafletOutput("plot"),
>>>   tableOutput("data")
>>> )
>>> #Set up server
>>> server <- function(input, output, session) {
>>>   #Draw map
>>>   output$plot <- renderLeaflet({
>>>   leaflet(tarrant_sp) %>% addTiles() %>%
>>>   addPolygons(label=~TRACTCE)
>>> })
>>>   #allegedly grab market clicks
>>>   output$data <- renderTable({
>>> nearPoints(tarrant_sp, input$plot_marker_click)
>>> print(input$plot_marker_click)
>>>   })
>>> }
>>> shinyApp(ui,server)
>>>
>>> I would like to get the values from the click and make calculations
>>> based on the tracts selected.  However, nothing is appearing in the
>>> input$plot_marker_click.
>>>
>>> Any suggestions much appreciated.
>>>
>>> Sincerely,
>>> Erin
>>>
>>>
>>> Erin Hodgess, PhD
>>> mailto: erinm.hodg...@gmail.com
>>>
>>>
>>> On Wed, Jun 1, 2022 at 9:03 AM Ben Tupper  wrote:
>>>
>>>> Hi Erin,
>>>>
>>>> This is a great place to ask questions - especially if you provide a
>>>> reproducible example.
>>>>
>>>> Cheers,
>>>> Ben
>>>>
>>>> On Wed, Jun 1, 2022 at 8:24 AM Erin Hodgess 
>>>> wrote:
>>>>
>>>>> Hello everyone;
>>>>>
>>>>> Can I ask a leaflet question here, please, or is that a topic for
>>>>> RStudio
>>>>> Community?
>>>>>
>>>>> Thanks,
>>>>> Erin
>>>>> --
>>>>> Erin Hodgess, PhD
>>>>> mailto: erinm.hodg...@gmail.com
>>>>>
>>>>> [[alternative HTML version deleted]]
>>>>>
>>>>> ___
>>>>> R-sig-Geo mailing list
>>>>> R-sig-Geo@r-project.org
>>>>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>>>>>
>>>>
>>>>
>>>> --
>>>> Ben Tupper (he/him)
>>>> Bigelow Laboratory for Ocean Science
>>>> East Boothbay, Maine
>>>> http://www.bigelow.org/
>>>> https://eco.bigelow.org
>>>>
>>>>
>>
>> --
>> Ben Tupper (he/him)
>> Bigelow Laboratory for Ocean Science
>> East Boothbay, Maine
>> http://www.bigelow.org/
>> https://eco.bigelow.org
>>
>>

-- 
Ben Tupper (he/him)
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Migrating from proj strings to WKT/EPSG

2021-11-22 Thread Ben Tupper
Doh!  Forehead slap!  How the heck did I overlook that simple
solution.  Thank you!

On Mon, Nov 22, 2021 at 2:51 PM Diego Hernangómez Herrero
 wrote:
>
> Hi Ben:
>
> I don't know if this is relevant for your question, but you can use 
> proj4strings with sf::st_crs() without using rgdal:
>
> ``` r
> proj <- "+proj=tmerc +datum=NAD83 +lon_0=-70d10 lat_0=42d50 
> k=.6667 x_0=90 y_0=0"
> sf::st_crs(proj)
>
> #> Coordinate Reference System:
> #>   User input: +proj=tmerc +datum=NAD83 +lon_0=-70d10 lat_0=42d50 
> k=.6667 x_0=90 y_0=0
> #>   wkt:
> #> PROJCRS["unknown",
> #> BASEGEOGCRS["unknown",
> #> DATUM["North American Datum 1983",
> #> ELLIPSOID["GRS 1980",6378137,298.257222101,
> #> LENGTHUNIT["metre",1]],
> #> ID["EPSG",6269]],
> #> PRIMEM["Greenwich",0,
> #> ANGLEUNIT["degree",0.0174532925199433],
> #> ID["EPSG",8901]]],
> #> CONVERSION["unknown",
> #> METHOD["Transverse Mercator",
> #> ID["EPSG",9807]],
> #> PARAMETER["Latitude of natural origin",42.8,
> #> ANGLEUNIT["degree",0.0174532925199433],
> #> ID["EPSG",8801]],
> #> PARAMETER["Longitude of natural origin",-70.16667,
> #> ANGLEUNIT["degree",0.0174532925199433],
> #> ID["EPSG",8802]],
> #> PARAMETER["Scale factor at natural origin",0.667,
> #> SCALEUNIT["unity",1],
> #> ID["EPSG",8805]],
> #> PARAMETER["False easting",90,
> #> LENGTHUNIT["metre",1],
> #> ID["EPSG",8806]],
> #>         PARAMETER["False northing",0,
> #> LENGTHUNIT["metre",1],
> #> ID["EPSG",8807]]],
> #> CS[Cartesian,2],
> #> AXIS["(E)",east,
> #> ORDER[1],
> #> LENGTHUNIT["metre",1,
> #> ID["EPSG",9001]]],
> #> AXIS["(N)",north,
> #> ORDER[2],
> #> LENGTHUNIT["metre",1,
> #> ID["EPSG",9001
> ```
>
>
> El lun, 22 nov 2021 a las 20:11, Ben Tupper () escribió:
>>
>> Hello,
>>
>> I have a spatial mesh that provides the following CRS.
>>
>> proj <- "proj=tmerc +datum=NAD83 +lon_0=-70d10 lat_0=42d50
>> k=.6667 x_0=90 y_0=0"
>>
>> To use this with the sf package it must be formed as Well Known Text
>> or a EPSG code. In this particular case there is no EPSG code in the
>> registry.
>>
>> My current workflow so I can use this data in sf is to leverage
>> showWKT() from the rgdal package to cast the proj string to WKT. The
>> following message is printed when the packages is loaded.
>>
>> > Please note that rgdal will be retired by the end of 2023, plan transition 
>> > to sf/stars/terra functions using GDAL and PROJ at your earliest 
>> > convenience.
>>
>>
>> rgdal::showWKT(proj) |> sf::st_crs(wkt)
>>
>> #> Coordinate Reference System:
>> #>   User input:
>> PROJCS["unknown",GEOGCS["unknown",DATUM["North_American_Datum_1983",SPHEROID["GRS
>> 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",42.8],PARAMETER["central_meridian",-70.16667],PARAMETER["scale_factor",0.667],PARAMETER["false_easting",90],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]
>> #>   wkt:
>> #> PROJCRS["unknown",
>> #> BASEGEOGCRS["unknown",
>> #> DATUM["North American Datum 1983",
>> #> ELLIPSOID["GRS 1980",6378137,298.257222101,
>> #> LENGTHUNIT["metre",1]],
>> #> 

[R-sig-Geo] Migrating from proj strings to WKT/EPSG

2021-11-22 Thread Ben Tupper
Hello,

I have a spatial mesh that provides the following CRS.

proj <- "proj=tmerc +datum=NAD83 +lon_0=-70d10 lat_0=42d50
k=.6667 x_0=90 y_0=0"

To use this with the sf package it must be formed as Well Known Text
or a EPSG code. In this particular case there is no EPSG code in the
registry.

My current workflow so I can use this data in sf is to leverage
showWKT() from the rgdal package to cast the proj string to WKT. The
following message is printed when the packages is loaded.

> Please note that rgdal will be retired by the end of 2023, plan transition to 
> sf/stars/terra functions using GDAL and PROJ at your earliest convenience.


rgdal::showWKT(proj) |> sf::st_crs(wkt)

#> Coordinate Reference System:
#>   User input:
PROJCS["unknown",GEOGCS["unknown",DATUM["North_American_Datum_1983",SPHEROID["GRS
1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",42.8],PARAMETER["central_meridian",-70.16667],PARAMETER["scale_factor",0.667],PARAMETER["false_easting",90],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]
#>   wkt:
#> PROJCRS["unknown",
#> BASEGEOGCRS["unknown",
#> DATUM["North American Datum 1983",
#> ELLIPSOID["GRS 1980",6378137,298.257222101,
#> LENGTHUNIT["metre",1]],
#> ID["EPSG",6269]],
#> PRIMEM["Greenwich",0,
#> ANGLEUNIT["degree",0.0174532925199433],
#> ID["EPSG",8901]]],
#> CONVERSION["unnamed",
#> METHOD["Transverse Mercator",
#> ID["EPSG",9807]],
#> PARAMETER["Latitude of natural origin",42.8,
#> ANGLEUNIT["degree",0.0174532925199433],
#> ID["EPSG",8801]],
#> PARAMETER["Longitude of natural origin",-70.16667,
#> ANGLEUNIT["degree",0.0174532925199433],
#> ID["EPSG",8802]],
#> PARAMETER["Scale factor at natural origin",0.667,
#> SCALEUNIT["unity",1],
#> ID["EPSG",8805]],
#> PARAMETER["False easting",90,
#> LENGTHUNIT["metre",1],
#> ID["EPSG",8806]],
#> PARAMETER["False northing",0,
#> LENGTHUNIT["metre",1],
#> ID["EPSG",8807]]],
#> CS[Cartesian,2],
#> AXIS["easting",east,
#> ORDER[1],
#> LENGTHUNIT["metre",1,
#> ID["EPSG",9001]]],
#> AXIS["northing",north,
#> ORDER[2],
#> LENGTHUNIT["metre",1,
#> ID["EPSG",9001

In the spirit of not leaving things to the last minute (that's never
happened before!), what are the current options for converting proj
strings to WKT that don’t use rgdal?

Cheers and thanks,
Ben

--
Ben Tupper (he/him)
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Binding columns of pixel values

2021-09-09 Thread Ben Tupper
Hi,

In general you won't be happy with column (or row) binding if you are
starting out with vectors of varying lengths.  That's cbind and rbind
are what I call rectangle-centric.  They want to produce rectangular
data, like matrices and data.frames.  How do they make a rectangle
from 6 vectors of varying lengths?

You don't say but I suspect that you are using either the raster or
terra packages.  Are you extracting different points from each of the
six layers?  If that is the case you could make a single long table of
the extracted values...

eA <- data.frame(name = "A", value = extract(rasterA, xyA)
eB <- data.frame(name = "B", value = extract(rasterB, xyB)
 ...

r <- do.call(rbind, list(eA, eB, ...))


I'm not sure if this is valuable to you or not, but below is an
example of a multilayer SpatRaster.  It won't work if your 6 raster
layers have different sizes and extents.  A set of 3 points are
extracted (one row per point) from the three layers.

f <- system.file("ex/meuse.tif", package="terra")
r <- rast(f)
r <- c(r, r*10, r*100)
names(r) <- LETTERS[1:3]

xy <- cbind(179000, 33)
xy <- rbind(xy-100, xy, xy+1000)
extract(r, xy)
#AB C
#1 378 3780 37800
#2 251 2510 25100
#3 208 2080 20800

Ben


On Thu, Sep 9, 2021 at 12:52 PM Enoch Gyamfi Ampadu  wrote:
>
> Dear List,
>
> I hope you are all well. Please I did an extraction of pixel values for 6
> land cover classes using *extract()*. Now I want to bind them into a
> single *data
> frame* but it is not working due to different lengths of columns. I have
> tried some *cbind* and at some point *rbind* but have still not been
> successful. I will be glad if anyone could assist me with an approach to
> use to bind the columns.
>
> Best regards,
>
> Enoch.
>
> --
> *Enoch Gyamfi - Ampadu, PhD*
>
> *FIDEP Foundation*
>
> *Spiritan University, *
>
> *S05, Ejisu, AR, Ghana*
>
> *Phone: +233 264308887 / +233 593630608*
>
> *email: egamp...@gmail.com *
>
>
> *skype: enoch.ampadu*
> *The highest evidence of nobility is self-control*.
>
> *A simple act of kindness creates an endless ripple*.
>
> [[alternative HTML version deleted]]
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



-- 
Ben Tupper (he/him)
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] question on the use of Leaflet for plotting points and rater GeoTIFF

2021-08-13 Thread Ben Tupper
Hi,

I don't think we can run the code since it isn't reproducible (see
https://CRAN.R-project.org/package=reprex
<https://cran.r-project.org/package=reprex> for help with that.)  But here
are some hints:

flipped color bar - I love to use RSeek.org which is an R-centric search
engine -  you may want to bookmark it or add it to your search engine list
if your browser supports that. https://rseek.org/?q=leaflet+flip+color+bar
This search hits a number of discussions on flipping the color bar.

color intensity - oh, there is so much discussion in the world about
colors.  By default raster images have opacity of 1 (fully opaque) when
rendered in leaflet, so really it is a matter of finding the color table
you want and then applying colorNumeric judiciously.  For me it comes down
to trial and error.  If you are looking for eye pop! then perhaps check out
the viridis options.  See ?colorNumeric

Cheers,
Ben

On Thu, Aug 12, 2021 at 2:24 PM Gabriel Cotlier  wrote:

> Dear Ben,
>
> Thanks a lot for your help!
> Actually it worked very well for me with the link you gave me.
> However, for some reason the numbers of the values in color scale goes
> from the lower values set at the top  (blue) of the sacale to the
> higher values set at the bottom (red ) and it would be better for me if it
> goes from from the lower values in the bottom (blue) to higher value in the
> top (red), since is temperature going from the lower to the higher.
>  Another issue I found a bit problematic for me to modify is that the
> color palette is too "light", for instance not like the color palette "Jet"
> in Matlab or Python, it seems as if the intensity of the colors of the
> temperature colors is low or light maybe is a transparency and should
> change opacity ?
>
> Maybe you or somebody knows a possible way to improve these two issues a
> bit ?
>
> Here is the code :
>
> # color palettes
> # pal <- colorNumeric(palette = "Spectral", values(raster), na.color =
> "transparent" , reverse = TRUE)
> pal <- colorNumeric(palette = "RdYlBu", values(raster), na.color =
> "transparent" , reverse = TRUE)
>
> # plot map
> leaflet() %>%
>   addTiles(urlTemplate = "
> https://mts1.google.com/vt/lyrs=s=en=app={x}={y}={z}=G;,
> attribution = 'Google')  %>%
>   addPolygons(data = polygon,weight=5,col = 'black')  %>%
>   addCircles(data = points, color = "White", radius = 500, fillOpacity =
> 1,opacity = 9)%>%
>   addRasterImage(raster, project = FALSE, colors = pal) %>%
>   addLegend(pal = pal, values = values(raster), title = "Temperature",
> opacity = 9)  # ,labFormat = labelFormat(transform = function(x) sort(x,
> decreasing = TRUE)))
>
> Thanks a lot again for your help.
> Kind regards,
> Gabriel
>
>
> On Thu, Aug 12, 2021 at 5:07 PM Ben Tupper  wrote:
>
>> Hi,
>>
>> See the "markers" and "raster images" sections here
>> http://rstudio.github.io/leaflet/markers.html
>>
>> Cheers,
>> Ben
>>
>> On Thu, Aug 12, 2021 at 5:02 AM Gabriel Cotlier 
>> wrote:
>>
>>> Hello.
>>>
>>> I would like to use Leaflet package to plot over a Google Satellite base
>>> map :
>>>
>>> 1.  a shapefile of polygon
>>> 2.  a shapefile of points
>>> 3,  a GeoTIFF image
>>>
>>> I could use the Leaflet package to get plotted successfully only the
>>> first
>>> Item of the list above with the following code :
>>>
>>> require(rgdal)
>>> library(rgeos)
>>> library(raster)
>>>
>>> shapeData <- raster::shapefile('Seattle_boundries.shp')
>>> shapeData <- spTransform(shapeData, CRS("+proj=longlat +ellps=GRS80"))
>>>
>>> leaflet() %>%
>>>   addTiles(urlTemplate = "
>>> https://mts1.google.com/vt/lyrs=s=en=app={x}={y}={z}=G;,
>>> attribution = 'Google')  %>%
>>>   addPolygons(data=shapeData,weight=5,col = 'red')
>>>
>>> How is it possible to find a way to complete the code above for plotting
>>> the item 2 and 3 as well in the same Leaflet figure.
>>>
>>> Is there any possible solution that can enable this task?
>>>
>>> Thanks for your help.
>>>
>>> Kind regards
>>> Gabriel
>>>
>>> [[alternative HTML version deleted]]
>>>
>>> ___
>>> R-sig-Geo mailing list
>>> R-sig-Geo@r-project.org
>>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>>>
>>
>>
>> --
>> Ben Tupper (he/him)
>> Bigelow Laboratory for Ocean Science
>> East Boothbay, Maine
>> http://www.bigelow.org/
>> https://eco.bigelow.org
>>
>>

-- 
Ben Tupper (he/him)
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] question on the use of Leaflet for plotting points and rater GeoTIFF

2021-08-12 Thread Ben Tupper
Hi,

See the "markers" and "raster images" sections here
http://rstudio.github.io/leaflet/markers.html

Cheers,
Ben

On Thu, Aug 12, 2021 at 5:02 AM Gabriel Cotlier  wrote:

> Hello.
>
> I would like to use Leaflet package to plot over a Google Satellite base
> map :
>
> 1.  a shapefile of polygon
> 2.  a shapefile of points
> 3,  a GeoTIFF image
>
> I could use the Leaflet package to get plotted successfully only the first
> Item of the list above with the following code :
>
> require(rgdal)
> library(rgeos)
> library(raster)
>
> shapeData <- raster::shapefile('Seattle_boundries.shp')
> shapeData <- spTransform(shapeData, CRS("+proj=longlat +ellps=GRS80"))
>
> leaflet() %>%
>   addTiles(urlTemplate = "
> https://mts1.google.com/vt/lyrs=s=en=app={x}={y}={z}=G;,
> attribution = 'Google')  %>%
>   addPolygons(data=shapeData,weight=5,col = 'red')
>
> How is it possible to find a way to complete the code above for plotting
> the item 2 and 3 as well in the same Leaflet figure.
>
> Is there any possible solution that can enable this task?
>
> Thanks for your help.
>
> Kind regards
> Gabriel
>
> [[alternative HTML version deleted]]
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>


-- 
Ben Tupper (he/him)
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Encoding of attributes in SpatVector (terra package)

2021-06-21 Thread Ben Tupper
Hi,

This quickly gets beyond my chops.  Have you considered filing a
reproducible example in the bug tracker?   You might search old issues
there first in case this has been resolved by others.  Also, search
with RSeek.org or the like.

https://cran.r-project.org/web/packages/terra/index.html

Cheers,
Ben

On Sun, Jun 20, 2021 at 9:36 PM Tim Elrick  wrote:
>
> Hi Ben,
>
> Sorry, now as plain text...
>
> Thanks for your response. I guess, that is a Windows encoding problem
> then, as I get (below I also included how they differ):
>
> ###
> identical(mtl.sf$NOM, mtl.spv$NOM)
> [1] FALSE
>  > sessionInfo()
> R version 4.1.0 (2021-05-18)
> Platform: x86_64-w64-mingw32/x64 (64-bit)
> Running under: Windows 10 x64 (build 17763)
>
> Matrix products: default
>
> locale:
> [1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252
> LC_MONETARY=English_Canada.1252
> [4] LC_NUMERIC=CLC_TIME=English_Canada.1252
>
> attached base packages:
> [1] stats graphics  grDevices utils datasets  methods   base
>
> other attached packages:
>   [1] sf_1.0-0terra_1.3-4 forcats_0.5.1   stringr_1.4.0
> dplyr_1.0.7 purrr_0.3.4 readr_1.4.0
>   [8] tidyr_1.1.3 tibble_3.1.2ggplot2_3.3.4   tidyverse_1.3.1
>
> loaded via a namespace (and not attached):
>   [1] tidyselect_1.1.1   haven_2.4.1lattice_0.20-44
> colorspace_2.0-1   vctrs_0.3.8generics_0.1.0
>   [7] utf8_1.2.1 rlang_0.4.11   e1071_1.7-7
> pillar_1.6.1   glue_1.4.2 withr_2.4.2
> [13] DBI_1.1.1  sp_1.4-5   dbplyr_2.1.1
> modelr_0.1.8   readxl_1.3.1   lifecycle_1.0.0
> [19] munsell_0.5.0  gtable_0.3.0   cellranger_1.1.0
> rvest_1.0.0raster_3.4-13  codetools_0.2-18
> [25] labeling_0.4.2 class_7.3-19   fansi_0.5.0
> broom_0.7.7Rcpp_1.0.6 KernSmooth_2.23-20
> [31] scales_1.1.1   backports_1.2.1classInt_0.4-3
> jsonlite_1.7.2 farver_2.1.0   fs_1.5.0
> [37] digest_0.6.27  hms_1.1.0  stringi_1.6.2  grid_4.1.0
>  cli_2.5.0  tools_4.1.0
> [43] magrittr_2.0.1 proxy_0.4-26   crayon_1.4.1
> pkgconfig_2.0.3ellipsis_0.3.2 xml2_1.3.2
> [49] reprex_2.0.0   lubridate_1.7.10   assertthat_0.2.1   httr_1.4.2
>  rstudioapi_0.13R6_2.5.0
> [55] units_0.7-2compiler_4.1.0
> ###
>
> Here is the difference:
> ###
>  > tail(mtl.sf$NOM)
> [1] "Montréal-Est""Anjou"
> "Pierrefonds-Roxboro" "Sainte-Anne-de-Bellevue"
> [5] "Verdun"  "Baie-d'Urfé"
>  > tail(mtl.spv$NOM)
> [1] "Montréal-Est"   "Anjou"
> "Pierrefonds-Roxboro" "Sainte-Anne-de-Bellevue"
> [5] "Verdun"  "Baie-d'Urfé"
> ###
>
> So, basically, vect() seems to have problems to interpret non-ASCII
> characters in Windows.
>
> Is there an easy way to fix that, e.g. by setting a parameter or is this
> a bug for the Windows edition?
>
> Thanks,
> Tim
>
> On 2021-06-15 18:32, Ben Tupper wrote:
> Hi,
>
>
> Alas, HTML mail gets mangled - try setting your email client to send
> plan text.
>
> I don't know what the NOM variable contents are supposed to look like,
> but I find they are identical.  Can you post to the list your evidence
> that shows how they differ and what makes one right versus the other
> wrong?  Also, always add the output of sessionInfo() as shown below.
>
> library(sf)
> library(terra)
>
> url <-
> "https://data.montreal.ca/dataset/00bd85eb-23aa-4669-8f1b-ba9a000e3dd8/resource/e9b0f927-8f75-458c-8fda-b5da65cc8b73/download/limadmin.geojson;
>
> mtl.sf <- read_sf(url)# convert sf object to SpatVector object
>
> mtl.spv <- vect(mtl.sf)
>
> identical(mtl.sf$NOM, mtl.spv$NOM)
> # [1] TRUE
>
> sessionInfo()
> # R version 4.0.3 (2020-10-10)
> # Platform: x86_64-apple-darwin17.0 (64-bit)
> # Running under: macOS Big Sur 10.16
> #
> # Matrix products: default
> # 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] terra_1.2-10 sf_0.9-8 dplyr_1.0.5
> #
> # loaded via a namespace (and not attached):
> #   [1] Rcpp_1.0.6 rstudioapi_0.13raster_3.4-5
> magrittr_2.0.1 units_0.7-1tidyselect_1.1.1
> # [7] lattice_0.20-41R6_2.5.0   rlang

Re: [R-sig-Geo] Encoding of attributes in SpatVector (terra package)

2021-06-15 Thread Ben Tupper
Hi,

Alas, HTML mail gets mangled - try setting your email client to send plan text.

I don't know what the NOM variable contents are supposed to look like,
but I find they are identical.  Can you post to the list your evidence
that shows how they differ and what makes one right versus the other
wrong?  Also, always add the output of sessionInfo() as shown below.

library(sf)
library(terra)

url <- 
"https://data.montreal.ca/dataset/00bd85eb-23aa-4669-8f1b-ba9a000e3dd8/resource/e9b0f927-8f75-458c-8fda-b5da65cc8b73/download/limadmin.geojson;

mtl.sf <- read_sf(url)# convert sf object to SpatVector object

mtl.spv <- vect(mtl.sf)

identical(mtl.sf$NOM, mtl.spv$NOM)
# [1] TRUE

sessionInfo()
# R version 4.0.3 (2020-10-10)
# Platform: x86_64-apple-darwin17.0 (64-bit)
# Running under: macOS Big Sur 10.16
#
# Matrix products: default
# 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] terra_1.2-10 sf_0.9-8 dplyr_1.0.5
#
# loaded via a namespace (and not attached):
#   [1] Rcpp_1.0.6 rstudioapi_0.13raster_3.4-5
magrittr_2.0.1 units_0.7-1tidyselect_1.1.1
# [7] lattice_0.20-41R6_2.5.0   rlang_0.4.11
fansi_0.4.2blob_1.2.1 tools_4.0.3
# [13] grid_4.0.3 KernSmooth_2.23-17 utf8_1.2.1
cli_2.5.0  e1071_1.7-6DBI_1.1.1
# [19] ellipsis_0.3.2 class_7.3-17   assertthat_0.2.1
tibble_3.1.1   lifecycle_1.0.0crayon_1.4.1
# [25] purrr_0.3.4codetools_0.2-16   vctrs_0.3.8
glue_1.4.2 sp_1.4-5   proxy_0.4-25
# [31] compiler_4.0.3 pillar_1.6.0   generics_0.1.0
classInt_0.4-3 pkgconfig_2.0.3

Cheers,
Ben


On Tue, Jun 15, 2021 at 11:57 AM Tim Elrick  wrote:
>
> Hi all,
>
> Does anyone know how to change encoding for attributes in a SpatVector
> (terra package)?
>
> library(sf) library(terra)
> # importing a geojson file as sf object url <-
> "https://data.montreal.ca/dataset/00bd85eb-23aa-4669-8f1b-ba9a000e3dd8/resource/e9b0f927-8f75-458c-8fda-b5da65cc8b73/download/limadmin.geojson;
> mtl.sf <- read_sf(url)# convert sf object to SpatVector object mtl.spv
> <- vect(mtl) # while mtl.sf$NOM # displays French letters correctly,
> mtl.spv$NOM # does not anymore Thanks, Tim
>
>
> [[alternative HTML version deleted]]
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



-- 
Ben Tupper (he/him)
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] How to identify the different discrete classes from a raster of land cover data (tif).

2021-03-02 Thread Ben Tupper
Hi,

I'm not familiar with the dataset, but I am guessing it is related to how
the labels are encoded. If that is the case, then it is possible the stored
class labels are not literally 1-23 but are 23 labels selected from the
range of 0-255.  You could do a brief check with ...

table(r[])

Cheers,
Ben



On Tue, Mar 2, 2021 at 12:15 PM Manuel Spínola  wrote:

> Dear list members,
>
> I am working with a .tif file from the Copernicus Global Land Service with
> land cover data.  The file has 23 discrete classes but the raster shows a
> continuous range of values (0 to 255).
>
> r =
>
> raster(W100N20_PROBAV_LC100_global_v3.0.1_2019-nrt_Discrete-Classification-map_EPSG-4326.tif)
>
> class  : RasterLayer
> dimensions : 20160, 20160, 406425600  (nrow, ncol, ncell)
> resolution : 0.0009920635, 0.0009920635  (x, y)
> extent : -100, -80, 0, 20  (xmin, xmax, ymin, ymax)
> crs: +proj=longlat +datum=WGS84 +no_defs
> source :
> /Users/manuelspinola/Documents/01-Manolo/R_OVS_material/landscape_ecology/datos_copernicus/W100N20_PROBAV_LC100_global_v3.0.1_2019-nrt_Discrete-Classification-map_EPSG-4326.tif
> names  :
> W100N20_PROBAV_LC100_global_v3.0.1_2019.nrt_Discrete.Classification.map_EPSG.4326
> values : 0, 255  (min, max)
>
>
>
> How can I recognize the different discrete classes included in the raster
> representing each land cover type.
>
> Manuel
>
>
> --
> *Manuel Spínola, Ph.D.*
> Instituto Internacional en Conservación y Manejo de Vida Silvestre
> Universidad Nacional
> Apartado 1350-3000
> Heredia
> COSTA RICA
> mspin...@una.cr 
> mspinol...@gmail.com
> Teléfono: (506) 8706 - 4662
> Personal website: Lobito de río <
> https://sites.google.com/site/lobitoderio/>
> Institutional website: ICOMVIS <http://www.icomvis.una.ac.cr/>
>
> [[alternative HTML version deleted]]
>
> ___________
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>


-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Crossing multiple raster to obtain a list of available values for each cell - LULCC package

2020-11-28 Thread Ben Tupper
Hello,

I am unfamiliar with the LULCC package, but what you describe sounds
to me like a simple extraction at one or more cell locations. At
least, that is what I think you describe here...

> That is, if I cross three rasters of one cell, with values 0, 1, 0, I
> would like to obtain a result that would tell me that the values of that
> cell are: 0, 1, 0.

I think that is a simple matter of raster::extract().

###
library(raster)

nr <- 3
nc <- 4
ncell <- nr * nc
m <- matrix(seq_len(ncell), nc = nc, nr = nr)

one <- raster(m)
two <- raster(m * 2)
three <- raster(m * 3)

S <- stack(one, two, three)

extract(S, c(1, 3, ncell))
#  layer.1 layer.2 layer.3
# [1,]   1   2   3
# [2,]   7  14  21
# [3,]  12  24  36
###

Have I understood the issue?

Ben

On Fri, Nov 27, 2020 at 6:59 AM David García Álvarez  wrote:
>
> Dear list,
>
> I want to cross multiple rasters with the same spatial resolution and
> extent and obtain as a result a summary raster or table that tells me
> which are the values that each cell acquires in the different rasters.
> That is, if I cross three rasters of one cell, with values 0, 1, 0, I
> would like to obtain a result that would tell me that the values of that
> cell are: 0, 1, 0.
>
> I have checked that the crosstab function of the raster packages allows
> to cross multiple rasters (by using a rasterstack). However, I do not
> know how to obtain the result I explained above.
>
> The LULCC package includes different functions to do that. However, in
> my experience, it is not really efficient and does not work well for
> rasters that are not very simple. The basic function of the package
> (Threemapcomparison) did not work for me or took for ages to run.
>
> Therefore, I would like to ask the community for help about: 1. ways to
> do the operation I described above, 2. to effectively work with the
> LULCC package in case I am doing something wrong or my issues with
> processing time / errors are not normal.
>
> Best,
> David
>
> _______
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Restricting geographical space for SDM analyses in R

2020-11-16 Thread Ben Tupper
Hi,

You can limit the domain of your modeling to irregular polygons such
as a coastline buffered to some +/- distance inshore/offshore, but the
ease of doing so depends upon your data and covariates. You haven't
provided much detail (well, none actually) so it's a challenge to
suggest anything.  For the vector/point data take a look at the sf
package (https://CRAN.R-project.org/package=sf) or sp
(https://CRAN.R-project.org/package=sp) packages, and for rasterized
data you could try raster (https://CRAN.R-project.org/package=raster),
terra (https://CRAN.R-project.org/package=terra) or stars
(https://CRAN.R-project.org/package=stars) packages.

Cheers,
Ben

On Mon, Nov 16, 2020 at 6:44 AM Francisco Borges
 wrote:
>
> I am conducting SDM analysis in R, and would like to restrict my
> predictions in the geographical space. I am aware of how to do it by
> cropping the world space with latitude and longitude, but my case is a
> little bit trickier.
>
> I want to restrict my analysis to only the coastal area (i.e. from ocean
> to, let's say a certain distance inland). I have yet to find a solution
> online to this question, but I am aware that using a shapefile it could
> work.
>
> I have zero knowledge of GIS, unfortunately, as I understand that this
> could be one of the solutions.
>
> I appreciate any info or suggestion you can provide me
>
> Best,
>
> *Francisco Borges*
>
> MARE – Marine and Environmental Sciences Centre
>
> Laboratório Marítimo da Guia - Faculdade de Ciências da Universidade de
> Lisboa
>
>
> Av. Nossa Senhora do Cabo, 939
>
> 2750-374 Cascais, Portugal
>
> Tel: +351 214 869 211
>
>
>
>
> publons.com/a/1504585/
> orcid.org/-0002-3911-0421
> http://www.mare-centre.pt/pt/user/8232
>
> [[alternative HTML version deleted]]
>
> ___________
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Create pixels neighborhood in a raster

2020-11-10 Thread Ben Tupper
Hi,

Thanks for updating the example - it is much easier.  I'm still not
sure of exactly what you are after, but my day is young and there is
still coffee to be had.

One thing I suggest is that you modify your computation of cells.  As
you have it, you are computing a matrix of x and y locations.

> cells<- xyFromCell(antscount, ants1)


But I really think you want to compute the cell numbers (1,2,3,...
left-to-right, top-to-bottom) from your original data locations (your
geo.form). Also, if I have followed correctly, I think you are looking
for a list of occupied cells regardless of how many ants in each cell.

> cells <- unique(cellFromXY(antscount, geo.form))

Then I get a series of plots that "look" right to me with little
squares across the plot.

Cheers,
Ben


On Mon, Nov 9, 2020 at 7:48 PM ASANTOS  wrote:
>
> Dear Ben,
>
> Sorry about of lot of mistakes, you are sure some part of code are
> confusing and/or with errors. I'll try again with some corrections:
>
> First, I have the rasterization process of ants presence (0 is absence)
> in a 10x10 units raster:
>
> #Packages
> library(spatstat)
> library(raster)
>
> #Selection of ants data set
> data(ants)
> geo.form<-cbind(x=ants$x,y=ants$y)
>
> #Definition of raster resolution - 10 units
> ants.w<-as.owin(ants)
> ext <- as(extent(c(ants.w$xrange,ants.w$yrange)), "SpatialPolygons")
> ants.res<-rasterToPoints(raster(ext, resolution = 10), spatial = TRUE)
> # coerce to SpatialPixelsDataFrame
> gridded(ants.res) <- TRUE
>
> #Rasterize
> antscount<- rasterize(geo.form, raster(ants.res), fun='count', background=0)
> values(antscount)[values(antscount) > 0] = 1
>
> #Vizualize
> plot(antscount)
>
> Now, I'd like to create 1 pixels around each pixel of ant presence
> (Total of 9 pixels in each ant presence in antscount raster):
>
> # For 1 pixel neighborhood
> neigh1 <- matrix(1L, nrow=3, ncol=3); neigh1[2,2] <- 0L
> ants1<-which(values(antscount)> 0)
> cells<- xyFromCell(antscount, ants1)
> e1<-adjacent(antscount, cells, directions=neigh1, pairs=FALSE)
> ng_coords1 <- xyFromCell(antscount, e1)
> points(ng_coords1, col="red")
>
> I need that's this new create pixels has 1 as value too.
>
> #Rasterize for 1 pixel neighborhood
> antscount.9<- rasterize(ng_coords1 , raster(ants.res), fun='count',
> background=0)
> plot(antscount.9)
>
> The problem is my ng_coords1 coordinates is wrong and just only in the
> top of the antscount raster, despite xyFromCell(antscount, ants1)
> condition. My goal is a new ant presence raster with 8 pixels
> surrounding the neigourhood of each pixel (ant) in the original
> antscount raster.
>
> Any ideas?
>
> Thanks in advanced,
>
> Alexandre
>
>
> --
> Alexandre dos Santos
> Geotechnologies and Spatial Statistics applied to Forest Entomology
> Instituto Federal de Mato Grosso (IFMT) - Campus Caceres
> Caixa Postal 244 (PO Box)
> Avenida dos Ramires, s/n - Vila Real
> Caceres - MT - CEP 78201-380 (ZIP code)
> Phone: (+55) 65 99686-6970 / (+55) 65 3221-2674
> Lattes CV: http://lattes.cnpq.br/1360403201088680
> OrcID: orcid.org/-0001-8232-6722
> ResearchGate: www.researchgate.net/profile/Alexandre_Santos10
> Publons: https://publons.com/researcher/3085587/alexandre-dos-santos/
> --
>
> Em 09/11/2020 19:41, Ben Tupper escreveu:
> > Hi,
> >
> > Your example isn't fully reproducible.  Or maybe it just has some little
> > errors.  I can't get past this spot...
> >
> > ants.w<-as.owin(ants)
> >> ext <- as(extent(c(ants.w$xrange,ants.w$yrange)), "SpatialPolygons")
> >> ants.res<-rasterToPoints(raster(ext, resolution = 10), spatial = TRUE)
> >> coordinates(ants.res) <- ~ x + y
> >>
> > You have requested that raster::rasterToPoints() return a spatial points
> > object, so there shouldn't be a need for sp::coordinates() to cast to a
> > spatial object.
> >
> > Also, I think you are invoking "antscounts" and "antscount" as the same
> > variable.  Maybe?  It's not clear to me.
> >
> > Finally, when you call raster::adjacent() you haven't defined the value for
> > the cells argument when computing e1 and e2.  What do you want them to be?
> >
> > I wish I could be more helpful.
> >
> > Cheers,
> > Ben
> >
> > On Mon, Nov 9, 2020 at 12:46 PM ASANTOS via R-sig-Geo <
> > r-sig-geo@r-project.org> wrote:
> >
> >> Dear r-sig-geo Members,
> >>
> >> I'd like to find any way to create 1 (total 9 pixels) and 2 pixels
> >> (total 25 pixels) surrounding the neighbor

Re: [R-sig-Geo] Create pixels neighborhood in a raster

2020-11-09 Thread Ben Tupper
Hi,

Your example isn't fully reproducible.  Or maybe it just has some little
errors.  I can't get past this spot...

ants.w<-as.owin(ants)
> ext <- as(extent(c(ants.w$xrange,ants.w$yrange)), "SpatialPolygons")
> ants.res<-rasterToPoints(raster(ext, resolution = 10), spatial = TRUE)
> coordinates(ants.res) <- ~ x + y
>

You have requested that raster::rasterToPoints() return a spatial points
object, so there shouldn't be a need for sp::coordinates() to cast to a
spatial object.

Also, I think you are invoking "antscounts" and "antscount" as the same
variable.  Maybe?  It's not clear to me.

Finally, when you call raster::adjacent() you haven't defined the value for
the cells argument when computing e1 and e2.  What do you want them to be?

I wish I could be more helpful.

Cheers,
Ben

On Mon, Nov 9, 2020 at 12:46 PM ASANTOS via R-sig-Geo <
r-sig-geo@r-project.org> wrote:

> Dear r-sig-geo Members,
>
> I'd like to find any way to create 1 (total 9 pixels) and 2 pixels
> (total 25 pixels) surrounding the neighborhood of each pixel (ant) in my
> plot image (antscount).
>
> In my example:
>
> #Packages
> library(spatstat)
> library(raster)
>
> #Selection of ants data set
> data(ants)
> geo.form<-cbind(x=ants$x,y=ants$y)
>
> #Definition of raster resolution - 10 units
> ants.w<-as.owin(ants)
> ext <- as(extent(c(ants.w$xrange,ants.w$yrange)), "SpatialPolygons")
> ants.res<-rasterToPoints(raster(ext, resolution = 10), spatial = TRUE)
> coordinates(ants.res) <- ~ x + y
> # coerce to SpatialPixelsDataFrame
> gridded(ants.res) <- TRUE
>
> #Rasterize
> antscount<- rasterize(geo.form, raster(ants.res), fun='count',
> background=0)
> values(antscount)[values(antscount) > 0] = 1
>
> #Vizualize
> plot(antscounts)
>
> Now, the selection of neighborhood pixels sounds easy, something like:
>
> # For 1 pixel neighborhood
> neigh1 <- matrix(1L, nrow=3, ncol=3)
> e1<-adjacent(antscounts, cells , directions=neigh1, pairs=FALSE)
> ng_coords1 <- xyFromCell(antscounts, e1)
>
> # For 2 pixel neighborhood
> neigh2 <- matrix(1L, nrow=5, ncol=5)
> e2<-adjacent(antscounts, cells , directions=neigh2, pairs=FALSE)
> ng_coords5 <- xyFromCell(antscounts, e2)
>
> But for the combination of all the information (0 and 1 new pixel
> values) and the new raster representation (antscounts) I don't have
> success. Please, any ideas?
>
> Thanks in advanced,
>
> Alexandre
>
> --
> Alexandre dos Santos
> Geotechnologies and Spatial Statistics applied to Forest Entomology
> Instituto Federal de Mato Grosso (IFMT) - Campus Caceres
> Caixa Postal 244 (PO Box)
> Avenida dos Ramires, s/n - Vila Real
> Caceres - MT - CEP 78201-380 (ZIP code)
> Phone: (+55) 65 99686-6970 / (+55) 65 3221-2674
> Lattes CV: http://lattes.cnpq.br/1360403201088680
> OrcID: orcid.org/-0001-8232-6722
> ResearchGate: www.researchgate.net/profile/Alexandre_Santos10
> Publons: https://publons.com/researcher/3085587/alexandre-dos-santos/
> --
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>


-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] "no applicable method" for focal() function in raster

2020-09-15 Thread Ben Tupper
Hello,

Unfortunately your email client formatted your message in HTML so the
content has been scrambled.  Best results experienced when the client is
configured to send plain text.

I think that issues is that lsm_l_condent() is expecting a raster (or
similar input).  See
https://cran.r-project.org/web/packages/landscapemetrics/landscapemetrics.pdf

Raster's focal() function slides along the raster pulling out cell values
(coincident with your focal window) and passes them to the function you
specify.  So as the docs for raster::focal descriibe, that function must be
configured to "take multiple numbers, and return a single number."
 landscapremetrics::lsm_l_condent is not configured that way.

Perhaps you need to create your own version of the function that just
operates on an input of numbers rather than an input of raster-like objects?

Cheers,
Ben

On Mon, Sep 14, 2020 at 4:42 PM Jaime Burbano Girón 
wrote:

> Hi everyone,
>
> I want to apply a moving window (3x3) to estimate conditional entropy
> (Nowosad & Stepinsky, 2019) over a heterogeneous landscape:
> *entropy=function(r){*
>
>
>
>
> *  entropy=lsm_l_condent(r, neighbourhood = 4, ordered = TRUE, base =
> "log2")  return(entropy$value)}w=matrix(1,3,3)result=focal(r, w,
> fun=entropy)*
>
> However, I get this error:
> *Error in .focal_fun(values(x), w, as.integer(dim(out)), runfun, NAonly) :
> *
> *Evaluation error: no applicable method for 'lsm_l_condent' applied to an
> object of class "c('double', 'numeric')".*
>
> But, when I run entropy function in the entire landscape it works:
>
> *> entropy(r)[1] 2.178874*
>
> *r* is a INT4U raster object:
>
>
>
>
>
>
> *class  : RasterLayer dimensions : 886, 999, 885114  (nrow, ncol,
> ncell)resolution : 300, 300  (x, y)extent : 934805.7, 1234506, 1006566,
> 1272366  (xmin, xmax, ymin, ymax)crs: +proj=tmerc
> +lat_0=4.5962004167 +lon_0=-74.077507917 +k=1 +x_0=100
> +y_0=100 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs values
>   : 99, 321113  (min, max)*
>
> There is any idea to solve the "no applicable method" error? Or any idea to
> estimate conditional entropy applying a moving window?
>
> Thanks in advance for the help.
>
> Best,
>
> Jaime
>
> [[alternative HTML version deleted]]
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>


-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Request for help about running a loop and reading .NC files

2020-03-23 Thread Ben Tupper
Hi,

Rolf is correct that you might consider enclosing your nc_open(...) with
try(nc_open(...)), and then testing if the value returned by try() inherits
from the "try-error" class. If there is no problem opening the NCDF file,
then it will return an "ncdf4" class object.

Also, you might isolate the file extraction stuff into a function to make
your life easier. Something like this (obviously not tested)...


### START
# extract data from a NCDF file
# @param filename the path and name of the file
# @return either NULL (for an exception) or a data.frame
extract_from_nc <- function(filename){

  nc <- try(nc_open(filename))
  if (inherits(nc, "try-error")){
# if it isn't a healthy NCDF file you will be here
x <- NULL
  } else {
# otherwise you will be here and you can run your extraction
mean1 <- ...
 ...
x <- as.data.frame(mean_chl_df)
write.csv(x, ... other stuff here ...)
nc_close(nc)
  }
  return(x)
}

flist <- list.files(path ="NCFiles/", pattern = "^.*\\.(nc|NC|Nc|Nc)$",
full.names = TRUE)

xx <- lapply(flist, extract_from_nc)
ix <- sapply(xx, is.null)# find the NULLS
xx <- xx[!ix]# remove them (if any)
if (length(xx) > 0) x <- do.call(rbind, xx)  # row bind what remains into
one data frame (in case that is helpful)
### END

I hope that helps.

Cheers,
Ben





On Mon, Mar 23, 2020 at 5:53 PM Bhaskar Mitra 
wrote:

> Hello Everyone,
>
> I have written a loop which reads hundreds of .nc files
> and extract information from each .nc file and
> exports that corresponding information as a csv file.
>
> The loop works fine until it encounters a .nc file which it cannot read
> and the loop stops. I would appreciate if anyone can suggest how can I
> modify
> the loop, whereby the loop will continue to run by bypassing those
> particular
> files which it cannot read.
>
> In the end I was also hoping to modify the loop such that it
> will generate a report which will inform me which
> files were not read by the loop.  The codes are given below
>
> Thanks,
> Bhaskar Mitra
> NAU
>
> #_--
>
>
> library(ncdf4)
> library(reshape2)
> library(dplyr)
> library(stringr)
>
>
> setwd("directory path")
>
> Output <- "directory path"
>
> flist <- list.files(path ="NCFiles/", pattern = "^.*\\.(nc|NC|Nc|Nc)$")
>
> for (i in 1: length(flist))
> {
>
>   nc <- nc_open(paste0("NCFiles/",flist[i]))
>   mean1 <- ncvar_get(nc,attributes(nc$dim)$names[3])
>   nc_close(nc)
>
>   mean_chl_df <- melt(mean1)
>   trial.table.df <-as.data.frame(mean_chl_df)
>
>
> write.csv(trial.table.df,paste0(Output,"/",tools::file_path_sans_ext(flist[i]),".csv"))
>
> }
>
> [[alternative HTML version deleted]]
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>


-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
East Boothbay, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] R spatial follows GDAL and PROJ development

2020-03-18 Thread Ben Tupper
This is very helpful - thank you!

On Wed, Mar 18, 2020 at 9:12 AM Roger Bivand  wrote:

> A new blog: "R spatial follows GDAL and PROJ development" has been
> published: https://www.r-spatial.org/r/2020/03/17/wkt.html.
>
> Those maintaining packages using sf or sp/rgdal, and authors of scripts
> using them should read the blog and be prepared to take rapid action when
> sf 0.9 is released and built using PROJ >= 6 and GDAL >= 3. An early
> release of rgdal (>= 1.5, probably 1.6.0, is also to be expected).
>
> Roger
>
> --
> Roger Bivand
> Department of Economics, Norwegian School of Economics,
> Helleveien 30, N-5045 Bergen, Norway.
> voice: +47 55 95 93 55; e-mail: roger.biv...@nhh.no
> https://orcid.org/-0003-2392-6140
> https://scholar.google.no/citations?user=AWeghB0J=en
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>


-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
West Boothbay Harbor, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] How to find distance between grid cell and point that lies in specified radius?

2020-02-06 Thread Ben Tupper
Hi,

I think you'll enjoy sf once you get going with it.

I am not familiar with the Cressman scheme, but you maybe able to do
step 1 with raster (either pointDistance() or distanceFromPoints() - I
can't quite recall).  In sf you could something like this..

library(raster)
library(sf)
library(units)
library(dplyr)

crs <- "+proj=poly +lat_0=0 +lon_0=-54 +x_0=500 +y_0=1000
+ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
r <- raster(nrows=9, ncols=18,
xmn=5153337, xmx=6570069,
ymn=7462732,ymx=8060416,
crs = crs)
r[] <- runif(ncell(r))

xy <- raster::xyFromCell(r, seq_len(ncell(r)))
xy <- lapply(seq_len(nrow(xy)), function(i) sf::st_point(xy[i,]))
xy <- sf::st_sfc(xy, crs = crs)

pts <- sampleRandom(r, 10, na.rm = TRUE, sp = TRUE) %>%
  sf::st_as_sfc()

d <- sf::st_distance(xy, pts)
threshold <- units::set_units(10, m)
d_within <- d <= threshold


d will be a [ncell x npoints] numeric matrix of distance from cell
locations to points
d_within will be a matrix [ncell x npoints] of logicals flagging which
are within your threshold (I used 100km)

Hope that helps start you off.

Cheers,
Ben



On Wed, Feb 5, 2020 at 9:12 PM Thiago V. dos Santos via R-sig-Geo
 wrote:
>
> Hello all,
>
> I am trying to implement a function in R to perform the Cressman scheme 
> (which corrects the values of a gridded field, say precipitation, based on 
> the closest observations available).
>
> It looks like it hasn't been done yet, but please let me know if you are 
> aware of any R package that implements the Cressman scheme.
>
> I have a raster and a spatial points layer (which I will call "stations"). A 
> toy example is provided below:
>
> ```
> library(raster)
>
>
> # create random raster
> r <- raster(nrows=9, ncols=18, xmn=5153337, xmx=6570069, ymn=7462732,
> ymx=8060416, crs = CRS("+proj=poly +lat_0=0 +lon_0=-54 
> +x_0=500 +y_0=1000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m 
> +no_defs"))
> r[] <- runif(ncell(r))
>
>
> # create spatial points
> pts <- sampleRandom(r, 10, na.rm = TRUE, sp = TRUE)
>
>
> # display everything
> plot(r)
> plot(pts, add=T, col="red", pch=16)
> ```
>
> The starting point of my analysis would be:
>
> 1) for each grid cell in the raster, identify the station(s) that lie *within 
> a radius of influence* (say 30 km);
>
> 2) for each station lying under the radius of influence, calculate a 
> distance-weighted expression that will be used later to correct the raster 
> values. Its formula is:
>
> W = (R2 - r2)/(R2 + r2)
>
> where R = influence radius and r = distance between the station and the grid 
> cell.
>
> 3) Based on the weighted correction factor W calculated above, update the 
> value of the grid cell using the expression W * (gridpoint - station). The 
> actual expression is a bit more sophisticated, but I want to get the general 
> method here.
>
> Based on some research, it looks like this could be done with sf. But since I 
> don't have any experience with that package, would someone more familiar 
> please point out some functions in sf or even other packages that could be 
> helpful to solve my problem?
>
> Thanks in advance,
>  -- Thiago V. dos Santos
>
> Postdoctoral Research Fellow
> Department of Climate and Space Science and Engineering
> University of Michigan
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
West Boothbay Harbor, Maine
http://www.bigelow.org/
https://eco.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] indexing multi-layer rasters

2020-01-17 Thread Ben Tupper
A, the lightbulb just went off!  That makes perfect sense.

Thanks!
Ben

On Fri, Jan 17, 2020 at 10:45 AM Bede-Fazekas Ákos  wrote:
>
> Hello Ben,
>
> I think you are absolutely right about "raster's implementation of `[[`
> is different than base R". But I don't agree on your interpretation on
> the logical indexing of rasters ('first logical index is used'). It is
> not the first one. The logical vector is coerced to integer, and c(TRUE,
> TRUE, TRUE) is treated as c(1, 1, 1), while c(TRUE, FALSE, TRUE) is
> treated as c(1, 0, 1). This is why it cause a 'not a valid subset' error
> (there is no sense of searching for the 0th layer of the RasterStack).
> If the first logical index was used, c(TRUE, TRUE, TRUE) and c(TRUE,
> FALSE, TRUE) would give exactly the same result, i.e a RasterLayer
> created from the first layer of the RasterStack.
>
> Have a nice weekend,
> Ákos
>
>
> 2020.01.17. 15:40 keltezéssel, Ben Tupper írta:
> > Hi,
> >
> > Thanks for this.  I think the root of my muddle is the mish-mash model
> > of a raster that I have in my head.  Depending upon what is most
> > convenient, I sometimes view a raster as a multi-dimensional array and
> > at other times as a list of single layer matrices.   If we step back
> > from logical indexing and use integers it is easier to identify
> > raster's slight variation on base R recursive indexing.  The example
> > below uses integer indices on a list and on a raster.
> >
> > Back to logical indexing, in a way it makes perfect sense as just the
> > first logical index is used; just as if() does.  But what is different
> > is that it uses that first logical index for each element in the index
> > vector.  That's why logo[[c(TRUE, TRUE, TRUE)]] yields red.1, red.2
> > and red.3.
> >
> > Thanks again and cheers,
> > Ben
> >
> >
> > library(raster)
> > x <- list(red = "R", green = "G", blue = "B")
> > logo <- raster::brick(system.file("external/rlogo.grd", package="raster"))
> >
> > # `[` index a list, get a list back (with NULL for not found)
> > x[c(1,3)]
> > # $red
> > # [1] "R"
> > #
> > # $green
> > # [1] "G"
> >
> > # `[` index a raster, get a matrix back (or vector for single layer)
> > logo[c(1,3)]
> > #  red green blue
> > # [1,] 255   255  255
> > # [2,] 255   255  255
> >
> > # `[[` recursive index of a list fails
> > x[[c(1,3)]]
> > # Error in x[[c(1, 3)]] : subscript out of bounds
> >
> > # `[[` index of a raster yields raster
> > # so raster's implementation of `[[` is different than base R
> > logo[[c(1,3)]]
> > # class  : RasterStack
> > # dimensions : 77, 101, , 2  (nrow, ncol, ncell, nlayers)
> > # resolution : 1, 1  (x, y)
> > # extent : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
> > # crs: +proj=merc +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
> > # names  : red, blue
> > # min values :   0,0
> > # max values : 255,  255
> >
> > On Fri, Jan 17, 2020 at 7:38 AM Bede-Fazekas Ákos  
> > wrote:
> >>
> >> Dear Ben,
> >> Although I cannot answer your question on why logical subsetting was not
> >> implemented in package raster, there is a very easy workaround:
> >> logo[[(1:nlayers(logo))[c(TRUE, TRUE, TRUE)]]]
> >> logo[[(1:nlayers(logo))[c(TRUE, FALSE, TRUE)]]]
> >>
> >> Also note that in case of lists '[[' does recursive indexing, and this
> >> type of logical indexing you are asking about works only with '['.
> >> HTH,
> >> Ákos Bede-Fazekas
> >> Hungarian Academy of Sciences
> >>
> >> 2020.01.16. 17:50 keltezéssel, Ben Tupper írta:
> >>> Hi,
> >>>
> >>> I usually avoid using logical indexes with multilayer rasters (stacks
> >>> and bricks), but I have never understood why indexing ala `[[` with
> >>> logicals isn't supported.  Below is an example that shows how it
> >>> doesn't work like the typical indexing with logicals.  I'm not asking
> >>> to have logical indices considered (although it would be handy), but
> >>> instead I really just want to understand why it is the way it is.  I
> >>> scanned over the introductory vignette (https://rspatial.org/raster)
> >>> and issues (https://github.com/rspatial/raster/issues) but found
> >>> nothing there.
> >>>
> >>> Thanks and cheers,
> >>> Ben
> >>>
> >>> ### START
> >

[R-sig-Geo] indexing multi-layer rasters

2020-01-16 Thread Ben Tupper
Hi,

I usually avoid using logical indexes with multilayer rasters (stacks
and bricks), but I have never understood why indexing ala `[[` with
logicals isn't supported.  Below is an example that shows how it
doesn't work like the typical indexing with logicals.  I'm not asking
to have logical indices considered (although it would be handy), but
instead I really just want to understand why it is the way it is.  I
scanned over the introductory vignette (https://rspatial.org/raster)
and issues (https://github.com/rspatial/raster/issues) but found
nothing there.

Thanks and cheers,
Ben

### START
library(raster)

logo <- raster::brick(system.file("external/rlogo.grd", package="raster"))

# red-red-red
logo[[c(TRUE, TRUE, TRUE)]]
# class  : RasterStack
# dimensions : 77, 101, , 3  (nrow, ncol, ncell, nlayers)
# resolution : 1, 1  (x, y)
# extent : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
# crs: +proj=merc +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
# names  : red.1, red.2, red.3
# min values : 0, 0, 0
# max values :   255,   255,   255

# red-red
logo[[c(TRUE, TRUE)]]
# class  : RasterStack
# dimensions : 77, 101, , 2  (nrow, ncol, ncell, nlayers)
# resolution : 1, 1  (x, y)
# extent : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
# crs: +proj=merc +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
# names  : red.1, red.2
# min values : 0, 0
# max values :   255,   255

# red
logo[[c(TRUE)]]
# class  : RasterLayer
# band   : 1  (of  3  bands)
# dimensions : 77, 101,   (nrow, ncol, ncell)
# resolution : 1, 1  (x, y)
# extent : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
# crs: +proj=merc +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
# source : /usr/lib64/R/library/raster/external/rlogo.grd
# names  : red
# values : 0, 255  (min, max)

logo[[c(TRUE, FALSE, TRUE)]]
#Error in .local(x, ...) : not a valid subset


#sessionInfo()
# R version 3.5.1 (2018-07-02)
# Platform: x86_64-redhat-linux-gnu (64-bit)
# Running under: CentOS Linux 7 (Core)
#
# Matrix products: default
# BLAS/LAPACK: /usr/lib64/R/lib/libRblas.so
#
# locale:
#   [1] LC_CTYPE=en_US.UTF-8   LC_NUMERIC=C
LC_TIME=en_US.UTF-8LC_COLLATE=en_US.UTF-8
# [5] LC_MONETARY=en_US.UTF-8LC_MESSAGES=en_US.UTF-8
LC_PAPER=en_US.UTF-8   LC_NAME=C
# [9] LC_ADDRESS=C   LC_TELEPHONE=C
LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
#
# attached base packages:
#   [1] stats graphics  grDevices utils datasets  methods   base
#
# other attached packages:
#   [1] raster_3.0-7 sp_1.3-2
#
# loaded via a namespace (and not attached):
#   [1] compiler_3.5.1   rgdal_1.4-8  tools_3.5.1  yaml_2.2.0
 Rcpp_1.0.3   codetools_0.2-15
# [7] grid_3.5.1   lattice_0.20-35

### END




-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
West Boothbay Harbor, Maine
http://www.bigelow.org/
https://eco.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Help

2020-01-09 Thread Ben Tupper
Your assignments that look like...

minx <-  rain_data_UTM at bbox[1,1]

are not valid R statements - and that will cause an error.  Instead,
obtain a matrix of the bounding box using the bbox() function.  Then
extract your coordinates from that. I think you want...

bb <- bbox(rain_data_UTM)
minx <- bb[1,1]
maxx <- bb[1,2]
miny <- bb[2,1]
maxy <- bb[2,2]

If you haven't seen this, https://www.rspatial.org/ , it is well worth your
time.  There are a lot of other great resources about using spatial data in
R.  Try searching the Rseek.org. Like this
https://rseek.org/?q=spatial+tutorials  It is a gold mine.


On Thu, Jan 9, 2020 at 1:42 PM Bakary Faty  wrote:

> Thank you for appreciated reply,
>
> I explane you exactly what I want to do with this R code attached.
> I want to adapt this code to my data to build an isohyet map.
> But i have some difficulties to adapt it to my case.
> I will be very happy when you will help my to adapt this R code (attached)
> to my case.
> You can find attached the you R code, my data file and my sahefile of
> watershed.
>
> Best regards
>
>
> Le jeu. 9 janv. 2020 à 17:47, Ben Tupper  a écrit :
>
>> Welcome to r-sig-geo!
>>
>> I don't think that you haven't provided us enough information so that we
>> can help.  On the other hand, does the example below using expand.grid help?
>>
>> minx <- 20
>> maxx <- 25
>> miny <- 31
>> maxy <- 36
>> pixel <- 1
>> grd <- expand.grid(x = seq(minx, maxx, by=pixel), y = seq(miny, maxy,
>> by=pixel))
>>
>> Ben
>>
>> On Thu, Jan 9, 2020 at 11:41 AM Bakary Faty  wrote:
>>
>>>
>>> Dear,
>>>
>>> I'm writing to express my wish to join R-sig-geo list users.
>>> I was doing a search on the net to know how to build an isohyet map and
>>> I came across this R code.
>>> However, I stumbled upon a problem from the line :
>>> grd <- expand.grid(x=seq(minx, maxx, by=pixel), y=seq(miny, maxy,
>>> by=pixel)),
>>> I get the following error message:
>>> default method not implemented for type 'S4'. I want to know how resolve
>>> this error.
>>>
>>> Also, I would like to ask you only at the line level:
>>> minx <- rain_data_UTM at bbox[1,1]
>>> maxx <- rain_data_UTM at bbox[1,2]
>>> miny <- rain_data_UTM at bbox[2,1]
>>> maxy <- rain_data_UTM at bbox[2,2],
>>> if I should limit myself to "rain_data_UTM" or write completely:
>>> rain_data_UTM at bbox[,].
>>>  By the way, this is the pointfile I reconstructed.
>>> You can find it attached to the mail.
>>>
>>> Thanks in advance
>>>
>>> Best regards
>>>
>>>
>>>
>>> Bakary
>>> ___
>>> R-sig-Geo mailing list
>>> R-sig-Geo@r-project.org
>>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>>>
>>
>>
>> --
>> Ben Tupper
>> Bigelow Laboratory for Ocean Science
>> West Boothbay Harbor, Maine
>> http://www.bigelow.org/
>> https://eco.bigelow.org
>>
>>
>
> --
>
>
>
> Bakary
>


-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
West Boothbay Harbor, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Help

2020-01-09 Thread Ben Tupper
Welcome to r-sig-geo!

I don't think that you haven't provided us enough information so that we
can help.  On the other hand, does the example below using expand.grid help?

minx <- 20
maxx <- 25
miny <- 31
maxy <- 36
pixel <- 1
grd <- expand.grid(x = seq(minx, maxx, by=pixel), y = seq(miny, maxy,
by=pixel))

Ben

On Thu, Jan 9, 2020 at 11:41 AM Bakary Faty  wrote:

>
> Dear,
>
> I'm writing to express my wish to join R-sig-geo list users.
> I was doing a search on the net to know how to build an isohyet map and I
> came across this R code.
> However, I stumbled upon a problem from the line :
> grd <- expand.grid(x=seq(minx, maxx, by=pixel), y=seq(miny, maxy,
> by=pixel)),
> I get the following error message:
> default method not implemented for type 'S4'. I want to know how resolve
> this error.
>
> Also, I would like to ask you only at the line level:
> minx <- rain_data_UTM at bbox[1,1]
> maxx <- rain_data_UTM at bbox[1,2]
> miny <- rain_data_UTM at bbox[2,1]
> maxy <- rain_data_UTM at bbox[2,2],
> if I should limit myself to "rain_data_UTM" or write completely:
> rain_data_UTM at bbox[,].
>  By the way, this is the pointfile I reconstructed.
> You can find it attached to the mail.
>
> Thanks in advance
>
> Best regards
>
>
>
> Bakary
> _______
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>


-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
West Boothbay Harbor, Maine
http://www.bigelow.org/
https://eco.bigelow.org

[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] raster: stackApply problems..

2019-11-20 Thread Ben Tupper
Hi,

That is certainly is unexpected to have two different naming styles.
It's not really solution to take to the bank, but you could simply
compose your own names assuming that the layer orders are always
returned in ascending index order.
Would that work for you

### start
library(raster)

# Compute layer names for stackApply output
#
# @param index numeric, 1-based layer indices used for stackApply function
# @param prefix character, prefix for names
# @return character layers names in index order
layer_names <- function(index = c(2,2,3,3,1,1), prefix = c("layer.",
"index_")[1]){
  paste0(prefix, sort(unique(index)))
}

indices <- c(2,2,3,3,1,1)

r <- raster()
values(r) <- 1
# simple sequential stack from 1 to 6 in all cells
s <- stack(r, r*2, r*3, r*4, r*5, r*6)
s

beginCluster(2)
res <- clusterR(s, stackApply, args = list(indices=indices, fun = mean))
raster::endCluster()
names(res) <- layer_names(indices, prefix = "foobar.")
res

res2 <- stackApply(s, indices, mean)
names(res2) <- layer_names(indices, prefix = "foobar.")
res2
### end


On Wed, Nov 20, 2019 at 1:36 AM Leonidas Liakos via R-sig-Geo
 wrote:
>
> This is not a reasonable solution. It is not efficient to run stackapply
> twice to get the right names. Each execution can take hours.
>
>
> Στις 20/11/2019 3:30 π.μ., ο Frederico Faleiro έγραψε:
> > Hi Leonidas,
> >
> > both results are in the same order, but the name is different.
> > You can rename the first as in the second:
> > names(res) <- names(res2)
> >
> > I provided an example to help you understand the logic.
> >
> > library(raster)
> > beginCluster(2)
> > r <- raster()
> > values(r) <- 1
> > # simple sequential stack from 1 to 6 in all cells
> > s <- stack(r, r*2, r*3, r*4, r*5, r*6)
> > s
> > res <- clusterR(s, stackApply, args = list(indices=c(2,2,3,3,1,1), fun =
> > mean))
> > res
> > res2 <- stackApply(s, c(2,2,3,3,1,1), mean)
> > res2
> > dif <- res - res2
> > # exatly the same order because the difference is zero for all layers
> > dif
> > # rename
> > names(res) <- names(res2)
> >
> > Best regards,
> >
> > Frederico Faleiro
> >
> > On Tue, Nov 19, 2019 at 4:15 PM Leonidas Liakos via R-sig-Geo <
> > r-sig-geo@r-project.org> wrote:
> >
> >> I run the example with clusterR:
> >>
> >> no_cores <- parallel::detectCores() -1
> >> raster::beginCluster(no_cores)
> >> ?? res <- raster::clusterR(inp, raster::stackApply, args =
> >> list(indices=c(2,2,3,3,1,1),fun = mean))
> >> raster::endCluster()
> >>
> >> And the result is:
> >>
> >>> res
> >> class?? : RasterBrick
> >> dimensions : 180, 360, 64800, 3?? (nrow, ncol, ncell, nlayers)
> >> resolution : 1, 1?? (x, y)
> >> extent : -180, 180, -90, 90?? (xmin, xmax, ymin, ymax)
> >> crs?? : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
> >> source : memory
> >> names?? : layer.1, layer.2, layer.3
> >> min values : 1.5, 3.5, 5.5
> >> max values : 1.5, 3.5, 5.5??
> >>
> >>
> >> layer.1, layer.2, layer.3 (?)
> >>
> >> So what corrensponds to what?
> >>
> >>
> >> If I run:
> >>
> >> res2 <- stackApply(inp,c(2,2,3,3,1,1),mean)
> >>
> >> The result is:
> >>
> >>> res2
> >> class  : RasterBrick
> >> dimensions : 180, 360, 64800, 3  (nrow, ncol, ncell, nlayers)
> >> resolution : 1, 1  (x, y)
> >> extent : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
> >> crs: +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
> >> source : memory
> >> names  : index_2, index_3, index_1
> >> min values : 1.5, 3.5, 5.5
> >> max values : 1.5, 3.5, 5.5
> >>
> >> There is no consistency with the names of the output and obscure
> >> correspondence with the indices in the case of clusterR
> >>
> >>
> >> [[alternative HTML version deleted]]
> >>
> >> ___
> >> R-sig-Geo mailing list
> >> R-sig-Geo@r-project.org
> >> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> >>
> >
>
>
> --
> Λιάκος Λεωνίδας, Γεωγράφος
> https://www.geographer.gr
> PGP fingerprint: 5237 83F8 E46C D91A 9FBB C7E7 F943 C9B6 8231 0937
>
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



-- 
Ben Tupper
Bigelow Laboratory for Ocean Science
West Boothbay Harbor, Maine
http://www.bigelow.org/
https://eco.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Selecting a range of longitude and latitudes

2019-04-18 Thread Ben Tupper
Hi,

The example you give is different than the one listed in the error message.  In 
your example you bind two 14-element vectors into a matrix of two columns.

cbind(103:116, 3:16)

But in the error you show the first vector is only 8 elements long...

cbind(103:110, 3:16)

When R encounters an attempt to bind columns of unequal length it will try to 
"recycle" the shorter vector as long as it is a multiple of the longer. In this 
case of binding an 8-element vector and a 14-element vector it fails.  

Note that shortening up the first vector to 7 does work since 7 is a multiple 
of 14...

cbind(103:109, 3:16)
  [,1] [,2]
 [1,]  1033
 [2,]  1044
 [3,]  1055
 [4,]  1066
 [5,]  1077
 [6,]  1088
 [7,]  1099
 [8,]  103   10
 [9,]  104   11
[10,]  105   12
[11,]  106   13
[12,]  107   14
[13,]  108   15
[14,]  109   16


Note how the sequence 103...109 appears twice in the first column.  Recycling 
is nice (and handy) until you get surprised by it.

Cheers,
Ben

> On Apr 18, 2019, at 8:37 PM, rain1290--- via R-sig-Geo 
>  wrote:
> 
> Hi there,
> I am trying to specify a range of longitudes and latitudes. I tried this 
> using the following:
> 
> 
> lonlat <- cbind(103:116, 3:16)  #This would specify a range of longitudes and 
> latitudes
> 
> However, I receive the following warning message:
> Warning message:
> In cbind(103:110, 3:16) :
>  number of rows of result is not a multiple of vector length (arg 1)
> 
> When I specify the longitude and latitude of a specific location, though, it 
> works just fine, like this:
> lonlat <- cbind(103, 3)
> 
> Am I specifying the ranges of coordinates incorrectly? The warning message 
> would suggest yes, but I do not understand why.
> Thanks, and any help with this would be greatly appreciated!
> ~Trav.~
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] [FORGED] Modifying the length of a matrix variable

2019-03-30 Thread Ben Tupper
Hi,

It looks like you are accessing a NetCDF file or it's kin.  Like Rolf, I'm 
challenged to understand from your description what you are after.  Assuming 
you do indeed have a NetCDF file and are using the ncdf4 package, you can 
retrieve the first 90 layers as shown below using the varid, start and count 
arguments to ncvar_get().  Obviously, this is untested since your data isn't 
available to us.

library(ncdf4)
filename = "/path/to/foo.nc"
ncObject <- nc_open(filename)
m <- ncvar_get(ncObject varid = "onedaymax", start = c(1,1,1), count = c(-1,-1, 
90))
nc_close(ncObject)


See more details and examples here... 
https://www.rdocumentation.org/packages/ncdf4/versions/1.16.1/topics/ncvar_get


You might also consider using the raster package which will retrieve multilayer 
georeferenced rasters for you from the same NetCDF file.

library(raster)
B <- brick(filename, varname = "onedaymax")
B <- B[[-c(91:95)]]# <- drop the last layers 91, 92, ...95

See the docs here... 
https://www.rdocumentation.org/packages/raster/versions/2.8-19/topics/brick

Cheers,
Ben

> On Mar 30, 2019, at 7:30 PM, rain1290--- via R-sig-Geo 
>  wrote:
> 
> Yes, I reproduced the example above and it works just fine (and is what I 
> want!!), but I cannot see why it does not work with my data, as it is a 
> 3-dimensional array (latitude, longitude and time). 
> This is what comes from print(Model4):
> 3 variables (excluding dimension variables):
>double onedaymax[lon,lat,time]   (Contiguous storage)  
>units: mm/day
>double fivedaymax[lon,lat,time]   (Contiguous storage)  
>units: mm/day
>short Year[time]   (Contiguous storage)  
> 
> 3 dimensions:
>time  Size:95
>lat  Size:64
>units: degree North
>lon  Size:128
>units: degree East
> I reviewed it over and over again, but I cannot see why this would not work?
> Thanks, 
> 
> 
> -Original Message-
> From: Rolf Turner 
> To: rain1290 
> Cc: r-sig-geo 
> Sent: Sat, Mar 30, 2019 6:49 pm
> Subject: Re: [FORGED] [R-sig-Geo] Modifying the length of a matrix variable
> 
> 
> On 31/03/19 11:14 AM, rain1...@aim.com wrote:
> 
>> Hi Rolf (and others),
>> 
>> I tried your suggestion, but when I used dim(Model4.chopped), it still 
>> shows 95 layers, as shown below:
>> 
>> 819295
>> 
>> I also find that the total number of cells is rather low for that many 
>> layers. I started with 778240 cells over 95 layers.
> 
> Well then you're doing something wrong, or there is something that you 
> haven't told us.
> 
> E.g.:
>> junk <- array(runif(64*128*95),dim=c(64,128,95))
>> junk.chopped <- junk[,,1:90]
>> dim(junk)
>> [1]  64 128  95
>> dim(junk.chopped)
>> [1]  64 128  90
> 
> Perhaps Model.4 has some structure other than that of an array. 
> (Originally you said it was a matrix.)
> 
> You really need to get your terminology and ideas *clear* in order to 
> have any hope of receiving useful advice.
> 
> I have no idea what you are on about in respect of "the number of 
> cells".  My mind-reading machine is in the repair shop.  I strongly 
> suspect that your thoughts are confused.
> 
> cheers,
> 
> Rolf
> 
> -- 
> Honorary Research Fellow
> Department of Statistics
> University of Auckland
> Phone: +64-9-373-7599 ext. 88276
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] editing a correlogram

2019-03-16 Thread Ben Tupper
Hi,

In this case the spdep::plot.spcor() function, which I think you are using, 
doesn't provide the mechanism for the caller to override the default pch value. 
 You can see this by looking at the pl.spcor function (as shown way below.)  I 
think it may be easiest for you to simply rewrite the function with the 
plotting parameters assigned as arguments.

Cheers,
Ben


> spdep::plot.spcor
function (x, main, ylab, ylim, ...) 
{
if (missing(main)) 
main <- x$var
if ((x$method == "I") || (x$method == "C")) {
lags <- as.integer(rownames(x$res))
to.plot <- which((x$res[, 3] > 0) & (x$res[, 3] != Inf))
sd2 <- rep(0, nrow(x$res))
sd2[to.plot] <- 2 * sqrt(x$res[to.plot, 3])
if (missing(ylim)) {
ylim <- range(c(x$res[, 1] + sd2, x$res[, 1] - sd2))
}
if (missing(ylab)) 
if (x$method == "I") 
ylab <- "Moran's  I"
if (x$method == "C") 
ylab <- "Geary's  C"
plot(lags, x$res[, 1], type = "p", pch = 18, ylim = ylim, 
main = main, ylab = ylab, xaxt = "n")
arrows(lags, x$res[, 1] + sd2, lags, x$res[, 1] - sd2, 
length = 0.1, angle = 90)
arrows(lags, x$res[, 1] - sd2, lags, x$res[, 1] + sd2, 
length = 0.1, angle = 90)
axis(1, at = lags)
abline(h = x$res[1, 2])
}
else {
res <- as.vector(x$res)
lags <- as.integer(names(x$res))
if (missing(ylim)) 
ylim <- c(-1, 1)
if (missing(ylab)) 
ylab <- "Spatial autocorrelation"
plot(lags, res, type = "h", ylim = ylim, main = main, 
ylab = ylab, lwd = 4, xaxt = "n")
axis(1, at = lags)
abline(h = 0)
}
}





> On Mar 16, 2019, at 1:16 PM, Leonardo Matheus Servino 
>  wrote:
> 
> I tried the function par() and arguments inside the plot(), but some
> parameters doesn't change.
> For example, the argument pch=, which changes the symbols that represents
> the points in the plot doesn't work.
> 
> 
> Em sáb, 16 de mar de 2019 às 13:48, Sarah Goslee  <mailto:sarah.gos...@gmail.com>>
> escreveu:
> 
>> Of course.
>> 
>> The ... argument to the plot method means that you can use standard
>> base graphics options to customize as you wish.
>> 
>> ?par gives the whole list, although they may not all be useful for
>> correlograms.
>> 
>> If you have specific questions after you try customizing to your
>> liking, the list can certainly help with details.
>> 
>> Sarah
>> 
>> On Sat, Mar 16, 2019 at 11:00 AM Leonardo Matheus Servino
>>  wrote:
>>> 
>>> Hello,
>>> 
>>> I've been tried to use the function "sp.correlogram". After plot the
>>> correlogram, I would like to edit the grafic's appearence, to publish it.
>>> It is possible?
>>> 
>>> Thanks
>>> 
>>> --
>>> Leonardo Matheus Servino
>>> Pós-Graduação em Evolução e Diversidade
>>> Universidade Federal do ABC - UFABC - Centro de Ciências Naturais e
>> Humanas
>>> 
>> 
>> --
>> Sarah Goslee (she/her)
>> http://www.numberwright.com
>> 
> 
> 
> -- 
> Leonardo Matheus Servino
> Pós-Graduação em Evolução e Diversidade
> Universidade Federal do ABC - UFABC - Centro de Ciências Naturais e Humanas
> 
> LED I - Laboratório de Evolução e Diversidade I - Bloco Delta, sala 202
> 
> Rua Arcturus, 3. Jardim Antares
> 09606-070 São Bernardo do Campo - SP
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org <mailto:R-sig-Geo@r-project.org>
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo 
> <https://stat.ethz.ch/mailman/listinfo/r-sig-geo>
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Error in running Maxent within biomod2

2019-03-14 Thread Ben Tupper
Hi,

You might want to verify that you have the required maxent jar file location 
properly identified.  See the MAXENT.Philips section here ...

https://www.rdocumentation.org/packages/biomod2/versions/3.3-7.1/topics/BIOMOD_ModelingOptions
 
<https://www.rdocumentation.org/packages/biomod2/versions/3.3-7.1/topics/BIOMOD_ModelingOptions>

Cheers,
Ben



> On Mar 14, 2019, at 5:01 PM, David L Carlson  wrote:
> 
> If you don't get an answer here, contact the biomod2 package maintainer. The 
> email address is shown on following webpage:
> 
> https://cran.r-project.org/web/packages/biomod2/index.html
> 
> or you can use the R command:
> 
> maintainer("biomod2")
> 
> David L. Carlson
> Department of Anthropology
> Texas A University
> 
> -Original Message-
> From: R-sig-Geo [mailto:r-sig-geo-boun...@r-project.org] On Behalf Of Lara 
> Silva
> Sent: Wednesday, March 13, 2019 6:17 PM
> To: r-sig-ecol...@r-project.org; r-sig-geo@r-project.org
> Subject: [R-sig-Geo] Error in running Maxent within biomod2
> 
> I got an error when running Maxent within biomod2
> 
> Running Maxent...Error in system(command = paste("java ",
> ifelse(is.null(Options@MAXENT.Phillips$memory_allocated),  :
> 
> What does it means?
> 
> Thanks
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 
> ___________
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] converting raster to netcdf .nc with keeping CRS information

2019-02-12 Thread Ben Tupper
Hi Ahmed,

I can confirm that on my system I get the same result as you.

Does your workflow confine you to using NetCDF?  I can successfully write/read 
to the native raster format.

r2 <- writeRaster(r, filename = "r001.grd", overwrite=TRUE)
r2 
#class   : RasterLayer 
#dimensions  : 1328, 1264, 1678592  (nrow, ncol, ncell)
#resolution  : 6250, 6250  (x, y)
#extent  : -395, 395, -395, 435  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=stere +lat_0=-90 +lat_ts=-70 +lon_0=0 +k=1 +x_0=0 +y_0=0 
+a=6378273 +b=6356889.449 +units=m +no_defs 
#data source : /home/btupper/r001.grd 
#names   : layer 
#values  : 0, 100  (min, max)


r3 <- raster("r001.grd")
r3 
#class   : RasterLayer 
#dimensions  : 1328, 1264, 1678592  (nrow, ncol, ncell)
#resolution  : 6250, 6250  (x, y)
#extent  : -395, 395, -395, 435  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=stere +lat_0=-90 +lat_ts=-70 +lon_0=0 +k=1 +x_0=0 +y_0=0 
+a=6378273 +b=6356889.449 +units=m +no_defs 
#data source : /home/btupper/r001.grd 
#names   : layer 
#values  : 0, 100  (min, max)

Ben

> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS/LAPACK: /usr/lib64/R/lib/libRblas.so

locale:
 [1] LC_CTYPE=en_US.UTF-8   LC_NUMERIC=C  
 [3] LC_TIME=en_US.UTF-8LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8   LC_NAME=C 
 [9] LC_ADDRESS=C   LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C   

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

other attached packages:
[1] raster_2.8-19 sp_1.3-1  ncdf4_1.16   

loaded via a namespace (and not attached):
[1] compiler_3.5.1   rgdal_1.3-6  Rcpp_1.0.0   codetools_0.2-15
[5] grid_3.5.1   lattice_0.20-35 





> On Feb 12, 2019, at 9:19 AM, Ahmed El-Gabbas  wrote:
> 
> Thanks Ben for your suggestion.
> 
> Adding *prj = TRUE *argument caused this error:
>   Error in ncdf4::ncvar_def(varname, varunit, list(xdim, ydim),
> NAvalue(x),  :
>   unused argument (prj = T)
> 
> Ahmed
> 
> On Tue, Feb 12, 2019 at 3:13 PM Ben Tupper  wrote:
> 
>> Hi,
>> 
>> Have you tried using the 'prj' argument to writeRaster?  I don't know that
>> it will be the solution, but according to ...
>> 
>> 
>> https://www.rdocumentation.org/packages/raster/versions/2.8-19/topics/writeRaster
>> 
>> It is documented among the '...' arguments.  Setting prj = TRUE will cause
>> the crs to be written to the file.
>> 
>> Cheers,
>> Ben
>> 
>> On Feb 12, 2019, at 8:34 AM, Ahmed El-Gabbas  wrote:
>> 
>> Hello all,
>> 
>> I am having a problem while converting a raster object as NetCDF (.nc)
>> file, with keeping the CRS information in the output file.
>> Here is a reproducible code:
>> 
>> require(raster)
>> require(ncdf4)
>> CurrTemp <- tempfile()
>> download.file(url = 
>> "https://seaice.uni-bremen.de/data/amsre/asi_daygrid_swath/s6250/2003/feb/Antarctic/asi-s6250-20030214-v5.hdf;,
>>  destfile = CurrTemp, mode = "wb", quiet = T)
>> r <- raster(CurrTemp)
>> r <- flip(r,2)
>> extent(r) <- c(-395, 395, -395, 435)
>> crs(r) <- "+proj=stere +lat_0=-90 +lat_ts=-70 +lon_0=0 +k=1 +x_0=0 +y_0=0 
>> +a=6378273 +b=6356889.449 +units=m +no_defs"
>> r# class   : RasterLayer # dimensions  : 1328, 1264, 1678592  (nrow, 
>> ncol, ncell)# resolution  : 6250, 6250  (x, y)# extent  : -395, 
>> 395, -395, 435  (xmin, xmax, ymin, ymax)# coord. ref. : 
>> +proj=stere +lat_0=-90 +lat_ts=-70 +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378273 
>> +b=6356889.449 +units=m +no_defs # data source : in memory# names : 
>> layer # values  : 0, 100  (min, max)
>> 
>> So far the raster object reads well, with CRS information included.
>> However, when I try to save it as .nc file, R prints "coord. ref. : NA",
>> and the produced file does not contain the CRS information.
>> 
>> writeRaster(r, filename = "O:/Ahmed/r001.nc", varname="IceConc",
>>overwrite=TRUE, format="CDF",
>>xname="Longitude", yname="Latitude")# class   : RasterLayer # 
>> dimensions  : 1328, 1264, 1678592  (nrow, ncol, ncell)# resolution  : 6250, 
>> 6250  (x, y)# extent  : -395, 395, -395, 435  (xmin, 
>> xmax, ymin, ymax)# coord. ref. : NA # data source : O:/Ahmed/r001.nc # names 
>> 

Re: [R-sig-Geo] converting raster to netcdf .nc with keeping CRS information

2019-02-12 Thread Ben Tupper
Hi,

Have you tried using the 'prj' argument to writeRaster?  I don't know that it 
will be the solution, but according to ...

https://www.rdocumentation.org/packages/raster/versions/2.8-19/topics/writeRaster
 
<https://www.rdocumentation.org/packages/raster/versions/2.8-19/topics/writeRaster>

It is documented among the '...' arguments.  Setting prj = TRUE will cause the 
crs to be written to the file.

Cheers,
Ben

> On Feb 12, 2019, at 8:34 AM, Ahmed El-Gabbas  wrote:
> 
> Hello all,
> 
> I am having a problem while converting a raster object as NetCDF (.nc) file, 
> with keeping the CRS information in the output file.
> Here is a reproducible code:
> require(raster)
> require(ncdf4)
> CurrTemp <- tempfile()
> download.file(url = 
> "https://seaice.uni-bremen.de/data/amsre/asi_daygrid_swath/s6250/2003/feb/Antarctic/asi-s6250-20030214-v5.hdf
>  
> <https://seaice.uni-bremen.de/data/amsre/asi_daygrid_swath/s6250/2003/feb/Antarctic/asi-s6250-20030214-v5.hdf>",
>  destfile = CurrTemp, mode = "wb", quiet = T)
> r <- raster(CurrTemp)
> r <- flip(r,2)
> extent(r) <- c(-395, 395, -395, 435)
> crs(r) <- "+proj=stere +lat_0=-90 +lat_ts=-70 +lon_0=0 +k=1 +x_0=0 +y_0=0 
> +a=6378273 +b=6356889.449 +units=m +no_defs"
> r
> # class   : RasterLayer 
> # dimensions  : 1328, 1264, 1678592  (nrow, ncol, ncell)
> # resolution  : 6250, 6250  (x, y)
> # extent  : -395, 395, -395, 435  (xmin, xmax, ymin, ymax)
> # coord. ref. : +proj=stere +lat_0=-90 +lat_ts=-70 +lon_0=0 +k=1 +x_0=0 
> +y_0=0 +a=6378273 +b=6356889.449 +units=m +no_defs 
> # data source : in memory
> # names   : layer 
> # values  : 0, 100  (min, max)
> So far the raster object reads well, with CRS information included.
> However, when I try to save it as .nc file, R prints "coord. ref. : NA", and 
> the produced file does not contain the CRS information.
> writeRaster(r, filename = "O:/Ahmed/r001.nc <http://r001.nc/>", 
> varname="IceConc",
> overwrite=TRUE, format="CDF",
> xname="Longitude", yname="Latitude")
> # class   : RasterLayer 
> # dimensions  : 1328, 1264, 1678592  (nrow, ncol, ncell)
> # resolution  : 6250, 6250  (x, y)
> # extent  : -395, 395, -395, 435  (xmin, xmax, ymin, ymax)
> # coord. ref. : NA 
> # data source : O:/Ahmed/r001.nc <http://r001.nc/> 
> # names   : IceConc 
> # zvar: IceConc
> 
> raster("O:/Ahmed/r001.nc <http://r001.nc/>")
> # class   : RasterLayer 
> # dimensions  : 1328, 1264, 1678592  (nrow, ncol, ncell)
> # resolution  : 6250, 6250  (x, y)
> # extent  : -395, 395, -395, 435  (xmin, xmax, ymin, ymax)
> # coord. ref. : NA 
> # data source : O:/Ahmed/r001.nc <http://r001.nc/> 
> # names   : IceConc 
> # zvar: IceConc
> Any solution?
> 
> N.B. I also sent the same question at stackoverflow 
> <https://stackoverflow.com/questions/54593552/saving-r-raster-to-netcdf-nc-file-with-keeping-crs-information>,
>  without a solution so far.
> 
> Thanks
> 
> ~
> Dr. Ahmed El-Gabbas,
> Ocean Acoustics Lab,
> Alfred-Wegener-Institut
> Helmholtz-Zentrum für Polar und Meeresforschung
> 
> My Website:  https://elgabbas.github.io 
> <https://elgabbas.github.io/>___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] How to get the coordinates (latitude/longitude) of a continent outline?

2019-02-02 Thread Ben Tupper
Hi,

Yes, I flubbed that.  I had it in my head that this...

https://www.naturalearthdata.com/downloads/110m-physical-vectors/110m-land/ 
<https://www.naturalearthdata.com/downloads/110m-physical-vectors/110m-land/>

... had Africa as a stand alone polygon, but that is not so.  Sorry for the 
noise.

Ben

> On Feb 2, 2019, at 10:17 AM, Sohrab Abbasnejad  
> wrote:
> 
> Dear Ben,
> 
> Thank you for your reply.
> 
> So far as I am aware, the rnaturalearth package provides information about 
> countries within a continent, states within countries and "world" coastline 
> (subsetting the coastline is not possible). Nevertheless, the package does 
> not include maps/data of "continents". What I need is the coordinates of 
> Africa's outline (as a single entity), not the coordinates of countries' 
> outlines within Africa.
> 
> Best,
> Sohrab
> 
> 
> On ‎Saturday‎, ‎February‎ ‎2‎, ‎2019‎ ‎03‎:‎38‎:‎25‎ ‎PM‎ ‎CET, Ben Tupper 
> wrote:
> 
> 
> Hi,
> 
> There is a whole world of options (sorry for the lame pun!), but I would 
> recommend checking out ROpenSci's rnaturalearth package
> 
> https://ropensci.org/tutorials/rnaturalearth_tutorial/ 
> <https://ropensci.org/tutorials/rnaturalearth_tutorial/>
> 
> https://CRAN.R-project.org/package=rnaturalearth 
> <https://cran.r-project.org/package=rnaturalearth>
> 
> Ben
> 
>> On Feb 2, 2019, at 8:36 AM, Sohrab Abbasnejad via R-sig-Geo 
>> mailto:r-sig-geo@r-project.org>> wrote:
>> 
>> Hello,
>> I would like to have the list of coordinates of the boundary (outline) of a 
>> continent (Africa). The "map" function from the "maps" package gives the 
>> coordinates for country outlines, but not the for the continents.
>> 
>> Does anybody have an idea where I can find the data?
>> 
>> Thank you!
>> 
>> Cheers,
>> Sohrab
>> 
>> 
>> 
>> 
>>  [[alternative HTML version deleted]]
>> 
>> ___
>> R-sig-Geo mailing list
>> R-sig-Geo@r-project.org <mailto:R-sig-Geo@r-project.org>
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 
> Ben Tupper
> Bigelow Laboratory for Ocean Sciences
> 60 Bigelow Drive, P.O. Box 380
> East Boothbay, Maine 04544
> http://www.bigelow.org <http://www.bigelow.org/>
> 
> Ecological Forecasting: https://eco.bigelow.org/ <https://eco.bigelow.org/>
> 
> 
> 
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] How to get the coordinates (latitude/longitude) of a continent outline?

2019-02-02 Thread Ben Tupper
Hi,

There is a whole world of options (sorry for the lame pun!), but I would 
recommend checking out ROpenSci's rnaturalearth package

https://ropensci.org/tutorials/rnaturalearth_tutorial/ 
<https://ropensci.org/tutorials/rnaturalearth_tutorial/>

https://CRAN.R-project.org/package=rnaturalearth 
<https://cran.r-project.org/package=rnaturalearth>

Ben

> On Feb 2, 2019, at 8:36 AM, Sohrab Abbasnejad via R-sig-Geo 
>  wrote:
> 
> Hello,
> I would like to have the list of coordinates of the boundary (outline) of a 
> continent (Africa). The "map" function from the "maps" package gives the 
> coordinates for country outlines, but not the for the continents.
> 
> Does anybody have an idea where I can find the data?
> 
> Thank you!
> 
> Cheers,
> Sohrab
> 
> 
> 
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] how to get an attribute from a raster layer

2018-12-28 Thread Ben Tupper
Hi,

You are looking for raster::getZ() but be aware that the Z value can be of any 
type - in this case I would guess it is a Date class so you will need to cast 
it to character using format() to get a label you desire.

https://www.rdocumentation.org/packages/raster/versions/2.8-4/topics/z-values


Cheers,
Ben
> On Dec 28, 2018, at 10:04 AM, Antonio Silva  wrote:
> 
> Dear list members
> 
> I need help to do something that should be easy but I could not execute.
> 
> I just want to plot a raster layer and use "z-value" as the title.
> 
> rst.data[[1]]
> class   : RasterLayer
> band: 1  (of  4  bands)
> dimensions  : 33, 45, 1485  (nrow, ncol, ncell)
> resolution  : 0.25, 0.25  (x, y)
> extent  : -50.25, -39, -29, -20.75  (xmin, xmax, ymin, ymax)
> coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
> data source : /mnt/.../dataset-sss-ssd-rep-monthly_2016-11-12_sos.nc
> names   : X2016.11.15.1
> z-value : 2016-11-15
> zvar: sos
> 
> Is it possible to extract the z-value value directly (2016-11-15)?
> 
> The best I could do was
> 
> plot(rst.data[[1]],main=substr(names(rst.data[[1]]),2,11))
> 
> Thanks a lot
> 
> Antonio Olinto
> Fisheries Institute
> São Paulo, Brazil
> 
>   [[alternative HTML version deleted]]
> 
> ___________
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] get data from nc file

2018-12-26 Thread Ben Tupper
Hi,

Yikes.  I don't think there is any other way as the attributes are sort of 
buried in the string; that's unfortunate.  I guess you could at least make a 
reusable function assuming you'll be doing this again or looking to pull other 
attributes.  Something like this...


#' Extract one of the GLobal Attributes of a TRMM NetCDF as a named vector 
#'
#' @param nc the ncdf4 object
#' @param name the name of the global attribute
#' @param sep the separator used to delimit fields in the attribute
#' @return named character vector of attributes
nc_att_split <- function(nc, name = "FileHeader", sep = ";\n"){

a1 <- ncdf4::ncatt_get(nc, 0)[[name[1]]]
if (is.null(a1)) return(a1)

a2 <- strsplit(a1,";\n", fixed = TRUE)[[1]]
aa <- strsplit(a2, "=", fixed = TRUE)

x <- sapply(aa,
function(s) x = if(length(s) <= 1) "" else s[2]
)   
names(x) <- sapply(aa,
function(s) x = if(length(s) <= 1) "unknown" else s[1]
)

x
}


nc <- ncdf4::nc_open("3B43.20080101.7A.HDF.nc")
x <- nc_att_split(nc)
as.Date(x[['StartGranuleDateTime']], format = "%Y-%m-%dT%H:%M:%OSZ")
[1] "2008-01-01"


Cheers,
Ben

> On Dec 26, 2018, at 3:42 PM, Antonio Silva  wrote:
> 
> Dear list members
> 
> I downloaded some nc files with precipitation data from
> https://pmm.nasa.gov/data-access/downloads/trmm (Level 3 3B43:
> Multisatellite Precipitation). For the image link see the global attribute
> "history" (below).
> 
> With ncdf4::nc_open I cloud open the file (nc.data <- nc_open("
> 3B43.20080101.7A.HDF.nc")
> 
> I want to extract the "StartGranuleDateTime" but it is inside the global
> attribute FileHeader (see below).
> 
> With ncatt_get(nc.data,0,"FileHeader")$value I got
> [1]
> "AlgorithmID=3B43;\nAlgorithmVersion=3B43_7.0;\nFileName=3B43.20080101.7A.HDF;\nGenerationDateTime=2012-11-29T19:12:01.000Z;\nStartGranuleDateTime=2008-01-01T00:00:00.000Z;\nStopGranuleDateTime=2008-01-31T23:59:59.999Z;\nGranuleNumber=;\nNumberOfSwaths=0;\nNumberOfGrids=1;\nGranuleStart=;\nTimeInterval=MONTH;\nProcessingSystem=PPS;\nProductVersion=7A;\nMissingData=;\n"
> 
> Is there any way to extract only the string "2008-01-01T00:00:00.000Z"?
> 
> The best I could do was
> as.Date(substr(strsplit(ncatt_get(nc.data,0,"FileHeader")$value,";\n")[[1]][5],22,45),"%Y-%m-%dT%H:%M:%OSZ")
> 
> but probably, I suppose, there must be a more direct way of getting the
> data. I appreciate any suggestions.
> 
> Best regards,
> 
> Antonio Olinto
> Fisheries Institute
> Brazil
> 
> nc.data
> File 3B43.20080101.7A.HDF.nc (NC_FORMAT_CLASSIC):
> 
> 1 variables (excluding dimension variables):
>float precipitation[nlat,nlon]
>units: mm/hr
>coordinates: nlon nlat
>_FillValue: -.900390625
> 
> 2 dimensions:
>nlon  Size:33
>long_name: longitude
>standard_name: longitude
>units: degrees_east
>nlat  Size:41
>long_name: latitude
>standard_name: latitude
>units: degrees_north
> 
>5 global attributes:
>Grid.GridHeader: BinMethod=ARITHMETIC_MEAN;
> Registration=CENTER;
> LatitudeResolution=0.25;
> LongitudeResolution=0.25;
> NorthBoundingCoordinate=50;
> SouthBoundingCoordinate=-50;
> EastBoundingCoordinate=180;
> WestBoundingCoordinate=-180;
> Origin=SOUTHWEST;
> 
>FileHeader: AlgorithmID=3B43;
> AlgorithmVersion=3B43_7.0;
> FileName=3B43.20080101.7A.HDF;
> GenerationDateTime=2012-11-29T19:12:01.000Z;
> StartGranuleDateTime=2008-01-01T00:00:00.000Z;
> StopGranuleDateTime=2008-01-31T23:59:59.999Z;
> GranuleNumber=;
> NumberOfSwaths=0;
> NumberOfGrids=1;
> GranuleStart=;
> TimeInterval=MONTH;
> ProcessingSystem=PPS;
> ProductVersion=7A;
> MissingData=;
> 
>FileInfo: DataFormatVersion=m;
> TKCodeBuildVersion=1;
> MetadataVersion=m;
> FormatPackage=HDF Version 4.2 Release 4, January 25, 2009;
> BlueprintFilename=TRMM.V7.3B43.blueprint.xml;
> BlueprintVersion=BV_13;
> TKIOVersion=1.6;
> MetadataStyle=PVL;
> EndianType=LITTLE_ENDIAN;
> 
>GridHeader: BinMethod=ARITHMETIC_MEAN;
> Registration=CENTER;
> LatitudeResolution=0.25;
> LongitudeResolution=0.25;
> NorthBoundingCoordinate=50;
> SouthBoundingCoordinate=-50;
> EastBoundingCoordinate=180;
> WestBoundingCoordinate=-180;
> Origin=SOUTHWEST;
> 
>history: 2018-12-26 17:57:56 GMT Hyrax-1.13.4
> htt

Re: [R-sig-Geo] How to sum area of adjacent patches?

2018-11-23 Thread Ben Tupper
Hi,

I think you may need to use raster::clump() and table() to label your regions.  
Check out an old message about clump...

https://stat.ethz.ch/pipermail/r-sig-geo/2017-January/025346.html

It's sort of cumbersome, but I think the following works...


library(raster)
r1<-raster(nrows=10, ncols=10, xmn=0, xmx=1, ymn=0, ymx=1)
r2<-raster(nrows=10, ncols=10, xmn=0, xmx=1, ymn=1, ymx=2)
r1[]<-c(rep(24,24), rep(0,76))
r2[]<-c(rep(0,86), rep(14,14))
par(mfrow=c(3,2)); plot(r1,main="r1"); plot(r2,main="r2")


r3<-merge(r1,r2) ; plot(r3, main="merged rasters")

r3 <- r3
r4[r4>0]<-38 ; plot(r4, main="desired result")

r5 <- clump(r3) ; plot(r5, main = 'clumped')
r5[is.na(r5)] <- 0

r5t <- table(getValues(r5))
for (i in names(r5t)[-1]){
id <- as.numeric(i)
print(id)
r5[r5 == id] <- r5t[i]
}

plot(r5, main = 'relabeled with area')


Cheers,
Ben

P.S. Years ago I used a language called IDL.  It's histogram function has an 
output keyword called reverse_indices (more here 
https://www.harrisgeospatial.com/docs/HISTOGRAM.html#H_835179117_677188 and 
here http://www.idlcoyote.com/tips/histogram_tutorial.html )  - super useful!  
Your situation just begs for that same solution in R.





> On Nov 23, 2018, at 5:13 PM, Hugo Costa  wrote:
> 
> Deal all,
> 
> I'm merging several rasters representing patches of forest, and the pixel
> values represent the area of the patches. The patches' area should be
> summed along the edges of the merged rasters. I provide a reproducible
> example. Any help is welcome.
> Hugo
> 
> library(raster)
> r1<-raster(nrows=10, ncols=10, xmn=0, xmx=1, ymn=0, ymx=1)
> r2<-raster(nrows=10, ncols=10, xmn=0, xmx=1, ymn=1, ymx=2)
> r1[]<-c(rep(24,24), rep(0,76))
> r2[]<-c(rep(0,86), rep(14,14))
> par(mfrow=c(2,2)); plot(r1,main="r1"); plot(r2,main="r2")
> 
> 
> r3<-merge(r1,r2) ; plot(r3, main="merged rasters")
> 
> # do something
> 
> r3[r3>0]<-38 ; plot(r3, main="desired result")
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] P-Tree

2018-09-03 Thread Ben Tupper
Hi,

Have you explored RSeek.org <http://rseek.org/>?

https://rseek.org/?q=p-tree <https://rseek.org/?q=p-tree>

Cheers,
Ben
> On Sep 3, 2018, at 11:16 AM, Jose luis Aguilar colmenero via R-sig-Geo 
>  wrote:
> 
> Hi,
> 
> I’m student PhD of Data science. I need know if exist any package that 
> contains p-tree algorithm.
> 
> Thank’s you
> 
> Enviado desde mi iPhone
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Adding great circle routes as polylines in Leaflet

2018-09-03 Thread Ben Tupper
 = c(37.8274879335485, 37.8274879335485,
>-90.9633701509553, 146.2727573458, 37.8274879335485, -90.9633701509553
>), LLat = c(21.4460561443517, 21.4460561443517, 25.2035802054683,
>47.6530892619773, 21.4460561443517, 25.2035802054683), DLon =
> c(-17.1597117430475,
>7.03639948506481, -73.4238157230412, 151.051220297802, 7.03639948506481,
>255.83509305644), DLat = c(24.2308740597312, 38.8907379374372,
>-25.8934046406896, -25.1880219406131, 38.8907379374372, 21.8130318388702
>)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
> ))
> 
> I would like to plot great circle routes between CommencingRegion to
> LoadingRegion and then from LoadingRegion to DischargeRegion for every row.
> Additionally, every row needs to be in a different color and the thickness
> needs to be proportional to AvgTCE. The last 6 variables in the data above
> are the coordinates in Lat Long for the commencing, loading and discharging
> regions respectively. I am quite clueless on how to go about achieving
> this. This is what I have tried and failed:
> 
> leaflet() %>%
>  addTiles() %>%
>  for(i in 1:6){
>
> addPolylines(data=gcIntermediate(c(ByRoute$CLon[i],ByRoute$CLat[i]),c(ByRoute$LLon[i],ByRoute$CLat[i]),n=100,addStartEnd
> = T,sp=T))
>  }
> 
> Regards
> Dhiraj Khanna
> Mob:09873263331
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Transform hexagonal to raster - a wife's question

2018-07-30 Thread Ben Tupper
If I were in your shoes I would be doing a hop-skip to ring Sarah Goslee's 
doorbell.  She's our resident ecology-spatial-textiles guru...

http://www.stringpage.com/ <http://www.stringpage.com/>







> On Jul 29, 2018, at 12:26 AM, chris english  
> wrote:
> 
> My wife showed me a beading pattern that she was working on that looks to
> my eye like a hexagonal grid, its called a peyote stitch, and she needs to
> transform it to a loom stitch, essentially a raster. In the beading world
> they suggest combining two rows into one. If asked, what have you tried, I
> would say I tried to duck, but... In practical application, the two rows
> equals one doesn't appear to preserve the desired pattern when beading the
> loom, probably something like netting out the half-steps when you're going
> from two rows to one = n+1 or n +2 for bead count on the combined row.
> 40x40 hex grid, OK, I'll get out my graph paper. Summer.
> 
> Thank you for your forbearance, and any very general thoughts appreciated,
> ie transforms sans datums & etc.
> 
> Chris
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Distance from not NA cells in a raster

2018-07-12 Thread Ben Tupper
Hi,

You may have solved this already, but I get tripped up on the "the distance 
from all not NA cells in a raster".  Is it the distance each NA cell is from 
each non-NA cell?  Also, I'm wondering why you want to know the distance to ALL 
non-NA cells - what is your big-picture purpose for wanting these distances?  

Cheers,
Ben

> On Jul 6, 2018, at 12:22 PM, Gregovich, Dave P (DFG) 
>  wrote:
> 
> Hi,
> I would like to obtain the distance from all not NA cells in a raster. This 
> works for smaller rasters, but seems difficult for the size of rasters (~ 
> 8000 pixel square)  I am working with.
> Below is what I've tried. I would be OK calling other software from R, or 
> using some parallelization, if it might help.
> Thanks so much for your help!  If I could just calculate this distance in two 
> hours or less (or so) I would be satisfied.
> Dave.
> 
> rm(list=ls())
> library(raster)
> 
> #make raster
> rast <- raster(nrow = 8000, ncol = 8000, ext = extent(0,1,0,1))
> 
> #generate cells to calculate distance from.
> rast[sample(8000^2, 1)] <- 1
> 
> #try two different methods...
> dist1 <- gridDistance(rast, origin = 1)#throws an error after x minutes
> #'Error: cannot allocate vector of size 3.8 Gb'
> dist2 <- distance(rast)#ran all night, R was hung up in the morning and had 
> to force shutdown.
> 
> ___
> Dave Gregovich
> Research Analyst
> Alaska Department of Fish and Game
> Division of Wildlife Conservation
> 802 3rd Street
> Douglas, AK 99824
> 907-465-4291
> ___
> 
> 
>   [[alternative HTML version deleted]]
> 
> _______
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] What is the Coordinate Reference System?

2018-06-18 Thread Ben Tupper
Hi,

I will blissfully proceed as I have in the past.   Thanks to each of you for 
the clear explanations.  

Cheers,
Ben

> On Jun 18, 2018, at 6:26 AM, Michael Sumner  wrote:
> 
> Agree with Edzer this application of eqc is anomalous and after it confused
> us initially we now ignore it and apply the unproblematic proj=longlat
> interpretation to these products (after checking).
> 
> I might explore the L3 products to find out why this occurred, but the
> ocean colour forum is the usual place to find discussion.
> 
> Cheers, Mike
> 
> On Mon, 18 Jun 2018, 15:59 Edzer Pebesma, 
> wrote:
> 
>> Plate carree is essentially a linear mapping of long and lat to x and y,
>> without changing aspect ratio (scale factor 1 at equator).
>> 
>> projecting long/lat towards plate caree using the proj4 string you
>> mention will however change the units from degrees to m. So while the
>> plots of of data in linear long/lat (with aspect ration 1) looks
>> identical to the one obtained in plate caree (with aspect ratio 1), the
>> numerical values along their axes are very different.
>> 
>> Many netcdf files carry a grid (raster) with the x and y coordinates of
>> grid cells (centers?) in another coordinate system, but the ones you
>> mention below don't, as far as I can tell. I think what they mean by
>> mentioning plate carree is just saying that this is a regular long/lat
>> degree grid; rather unlucky wording IMO.
>> 
>> On 06/15/2018 08:14 PM, Ben Tupper wrote:
>>> Hi,
>>> 
>>> That's an interesting approach.
>>> 
>>> On the other hand, sometimes I get bitten (well, muddled really) when I
>> use raster to determine the crs of a ncdf resource.  It all sort of depends.
>>> 
>>> Below is an example for Aqua MODIS imagery from OBPG (
>> https://oceandata.sci.gsfc.nasa.gov/MODIS-Aqua/Mapped/Daily/9km/sst/2017/
>> <https://oceandata.sci.gsfc.nasa.gov/MODIS-Aqua/Mapped/Daily/9km/sst/2017/>).
>> The OBPG docs (https://oceancolor.gsfc.nasa.gov/products/ <
>> https://oceancolor.gsfc.nasa.gov/products/>) state that the data is
>> served up as 'Plate Carrée' which I think has a crs ...
>>> 
>>> '+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84
>> +datum=WGS84 +units=m +no_defs '
>>> 
>>> ... as described here http://spatialreference.org/ref/epsg/32662/ <
>> http://spatialreference.org/ref/epsg/32662/>
>>> 
>>> You can see below that raster comes up with...
>>> 
>>> '+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0'
>>> 
>>> ... which is http://spatialreference.org/ref/epsg/4326/ <
>> http://spatialreference.org/ref/epsg/4326/>
>>> 
>>> Explicitly setting the crs while reading doesn't help.  I have never
>> resolved if it is an OBPG documentation bug, my confusion about
>> projections, or some other mystery.  So, my usual practice is to assume
>> that raster makes the right call.
>>> 
>>>  start
>>> 
>>> library(raster)
>>> URI = '
>> https://oceandata.sci.gsfc.nasa.gov/cgi/getfile/A2017175.L3m_DAY_SST_sst_9km.nc
>> '
>>> 
>>> # ~3.8MB
>>> ok = download.file(URI, basename(URI))
>>> 
>>> R = raster::raster(basename(URI), varname = 'sst')
>>> R
>>> # class   : RasterLayer
>>> # dimensions  : 2160, 4320, 9331200  (nrow, ncol, ncell)
>>> # resolution  : 0.0834, 0.0834  (x, y)
>>> # extent  : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
>>> # coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
>>> # data source : /Users/Shared/code/R/others/record/spnc/
>> A2017175.L3m_DAY_SST_sst_9km.nc
>>> # names   : Sea.Surface.Temperature
>>> # zvar: sst
>>> 
>>> S = raster::raster(basename(URI), varname = "sst", crs = '+proj=eqc
>> +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84
>> +units=m +no_defs')
>>> # Warning message:
>>> # In .getProj(prj, crs) :
>>> #  argument "crs" ignored because the file provides a crs
>>> 
>>>  end
>>> 
>>> 
>>> Cheers,
>>> Ben
>>> 
>>> 
>>>> On Jun 14, 2018, at 6:42 PM, Michael Sumner  wrote:
>>>> 
>>>> Try raster::projection(raster::raster(a)) first, then delve if necessary
>>>> into the ncdump summary with print(raster::raster(a)))
>>>> 
>>>> But, raster(a) may be enough here? To get that stuff more directly from
>&g

Re: [R-sig-Geo] What is the Coordinate Reference System?

2018-06-15 Thread Ben Tupper
Hi,

That's an interesting approach.  

On the other hand, sometimes I get bitten (well, muddled really) when I use 
raster to determine the crs of a ncdf resource.  It all sort of depends.

Below is an example for Aqua MODIS imagery from OBPG 
(https://oceandata.sci.gsfc.nasa.gov/MODIS-Aqua/Mapped/Daily/9km/sst/2017/ 
<https://oceandata.sci.gsfc.nasa.gov/MODIS-Aqua/Mapped/Daily/9km/sst/2017/>).  
The OBPG docs (https://oceancolor.gsfc.nasa.gov/products/ 
<https://oceancolor.gsfc.nasa.gov/products/>) state that the data is served up 
as 'Plate Carrée' which I think has a crs ...

'+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 
+units=m +no_defs ' 

... as described here http://spatialreference.org/ref/epsg/32662/ 
<http://spatialreference.org/ref/epsg/32662/>

You can see below that raster comes up with...

'+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0' 

... which is http://spatialreference.org/ref/epsg/4326/ 
<http://spatialreference.org/ref/epsg/4326/>

Explicitly setting the crs while reading doesn't help.  I have never resolved 
if it is an OBPG documentation bug, my confusion about projections, or some 
other mystery.  So, my usual practice is to assume that raster makes the right 
call.

 start

library(raster)
URI = 
'https://oceandata.sci.gsfc.nasa.gov/cgi/getfile/A2017175.L3m_DAY_SST_sst_9km.nc'

# ~3.8MB
ok = download.file(URI, basename(URI))

R = raster::raster(basename(URI), varname = 'sst')
R
# class   : RasterLayer
# dimensions  : 2160, 4320, 9331200  (nrow, ncol, ncell)
# resolution  : 0.0834, 0.0834  (x, y)
# extent  : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
# data source : 
/Users/Shared/code/R/others/record/spnc/A2017175.L3m_DAY_SST_sst_9km.nc
# names   : Sea.Surface.Temperature
# zvar: sst

S = raster::raster(basename(URI), varname = "sst", crs = '+proj=eqc +lat_ts=0 
+lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')
# Warning message:
# In .getProj(prj, crs) :
#  argument "crs" ignored because the file provides a crs

 end


Cheers,
Ben


> On Jun 14, 2018, at 6:42 PM, Michael Sumner  wrote:
> 
> Try raster::projection(raster::raster(a)) first, then delve if necessary
> into the ncdump summary with print(raster::raster(a)))
> 
> But, raster(a) may be enough here? To get that stuff more directly from the
> NetCDF API you have to use the inq and att functions of ncdf4 or RNetCDF
> and that's no fun.
> 
> I'd also try raster(rgdal::readGDAL(a)) which is a totally different but
> equivalent read path.
> 
> Cheers, Mike
> 
> On Thu, 14 Jun 2018, 11:03 Sergio Ibarra,  wrote:
> 
>> Greetings,
>> 
>> I'm want to read NetCDF spatial data from a meteorological model (WRF
>> model). The NetCDF can have one of these three projections:
>> 
>> Polar stereographic
>> Lambert conformal
>> Mercator projection
>> 
>> (See figure
>> 
>> https://user-images.githubusercontent.com/27447280/41389756-ed23f91a-6f68-11e8-961e-6ba901913c54.png
>> )
>> 
>> What is the  Coordinate Reference System for each case?
>> 
>> Thanks!
>> 
>> Here an example with ncdf4 and raster:
>> 
>> library(ncdf4)
>> library(raster)
>> a <- tempfile()
>> download.file(url = "
>> http://www.unidata.ucar.edu/software/netcdf/examples/wrfout_v2_Lambert.nc
>> ",
>>  destfile = a) #78 Mb
>> wrf <- nc_open(a)
>> paste("The file has",wrf$nvars,"variables")
>> paste("The file has",names(wrf$var))
>> lat <- ncvar_get( wrf, "XLAT" )
>> lon <- ncvar_get( wrf, "XLONG" )
>> t2 <- ncvar_get( wrf, "T2" ) - 273.15
>> dim(t2) #73 60 13
>> #image
>> image(t2[, , 12])
>> # raster
>> rt2 <- raster(t(t2[1:dim(t2)[1],
>>   dim(t2)[2]:1,
>>   12]),
>>  xmn = min(lon),
>>  xmx = max(lon),
>>  ymn = min(lat),
>>  ymx = max(lat),
>> *  crs="+init=epsg:4326") # ???*
>> spplot(rt2)
>> 
>> 
>> 
>> --
>> ​Sergio Ibarra Espinosa
>> Post Doc
>> PhD in Atmospheric Sciences
>> Instituto de Astronomia, Geofísica e Ciências Atmosféricas
>> Universidade de São Paulo
>> Rua do Matão, 1226
>> São Paulo-SP - Brasil -
>> 05508-090
>> +55-11-97425-3791
>> Skype: sergio_ibarra1
>> 
>>        [[alternative HTML version deleted]]
>> 
>> ___
>> R-sig-Geo mailing list
>> R-sig-Ge

Re: [R-sig-Geo] CRAN releases of sp, rgdal and rgeos

2018-06-11 Thread Ben Tupper
99  RMF Raster Matrix Format   
TRUE FALSE TRUE
100 ROI_PAC   ROI_PAC raster   
TRUE FALSE TRUE
101  RPFTOC Raster Product Format TOC format  
FALSE FALSE TRUE
102 RS2   RadarSat 2 XML Product  
FALSE FALSE TRUE
103 RSTIdrisi Raster A.1   
TRUE  TRUE TRUE
104SAFE  Sentinel-1 SAR SAFE Product  
FALSE FALSE TRUE
105SAGA SAGA GIS Binary Grid (.sdat)   
TRUE  TRUE TRUE
106SAR_CEOS   CEOS SAR Image  
FALSE FALSE TRUE
107SDTS  SDTS Raster  
FALSE FALSE TRUE
108   SENTINEL2   Sentinel 2  
FALSE FALSE TRUE
109 SGISGI Image File Format 1.0   
TRUE FALSE TRUE
110  SNODASSnow Data Assimilation System  
FALSE FALSE TRUE
111 SRP  Standard Raster Product (ASRP/USRP)  
FALSE FALSE TRUE
112 SRTMHGT  SRTMHGT File Format  
FALSE  TRUE TRUE
113Terragen Terragen heightfield   
TRUE FALSE TRUE
114 TIL  EarthWatch .TIL  
FALSE FALSE TRUE
115 TSX   TerraSAR-X Product  
FALSE FALSE TRUE
116 USGSDEM   USGS Optional ASCII DEM (and CDED)  
FALSE  TRUE TRUE
117   VICAR  MIPL VICAR file  
FALSE FALSE TRUE
118 VRT   Virtual Raster   
TRUE  TRUE TRUE
119 WCS OGC Web Coverage Service  
FALSE FALSE TRUE
120 WMS  OGC Web Map Service  
FALSE  TRUE TRUE
121WMTS OGC Web Mab Tile Service  
FALSE  TRUE TRUE
122 XPMX11 PixMap Format  
FALSE  TRUE TRUE
123 XYZASCII Gridded XYZ  
FALSE  TRUE TRUE
124ZMap   ZMap Plus Grid  
FALSE  TRUE TRUE

> On Jun 11, 2018, at 3:54 PM, Roger Bivand  wrote:
> 
> On Mon, 11 Jun 2018, Ben Tupper wrote:
> 
>> Hi,
>> 
>> I used CRAN binary ala ...
>> 
>>> install.packages("rgdal")
>> 
>> I used that same for sp and rgeos.
> 
> Good, thanks. They probably do not have the very latest versions of the 
> external dependencies, but do work and provide a reasonable selection of GDAL 
> drivers.
> 
> Roger
> 
>> 
>> Ben
>> 
>> 
>>> On Jun 11, 2018, at 3:45 PM, Roger Bivand  wrote:
>>> 
>>> On Mon, 11 Jun 2018, Ben Tupper wrote:
>>> 
>>>> Hi,
>>>> 
>>>> I have been able to install all three without issue.  I have encountered 
>>>> no issues with usage.
>>> 
>>> Ben,
>>> 
>>> Thanks for this report. How did you install rgdal - CRAN binary (now at 
>>> 1.3.2 for R 3.5.0) or source install using GDAL and PROJ installed in what 
>>> way? It's useful to record ways in which installation on OSX has been 
>>> accomplished.
>>> 
>>> Roger
>>> 
>>> 
>>> 
>>>> 
>>>>> sessionInfo()
>>>> R version 3.5.0 (2018-04-23)
>>>> Platform: x86_64-apple-darwin15.6.0 (64-bit)
>>>> Running under: macOS Sierra 10.12.6
>>>> 
>>>> Matrix products: default
>>>> BLAS: 
>>>> /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
>>>> LAPACK: 
>>>> /Library/Frameworks/R.framework/Versions/3.5/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] rgeos_0.3-28 rgdal_1.3-2  sp_1.3-1
>>>> 
>>>> loaded via a namespace (and not attached):
>>>> [1] compiler_3.5.0  tools_3.5.0 grid_3.5.0  lattice_0.20-35
>>>> 
>>>> Thanks for all you do!
>>>> 
>>>

Re: [R-sig-Geo] CRAN releases of sp, rgdal and rgeos

2018-06-11 Thread Ben Tupper
Hi,

I used CRAN binary ala ...

> install.packages("rgdal")

I used that same for sp and rgeos.  

Ben


> On Jun 11, 2018, at 3:45 PM, Roger Bivand  wrote:
> 
> On Mon, 11 Jun 2018, Ben Tupper wrote:
> 
>> Hi,
>> 
>> I have been able to install all three without issue.  I have encountered no 
>> issues with usage.
> 
> Ben,
> 
> Thanks for this report. How did you install rgdal - CRAN binary (now at 1.3.2 
> for R 3.5.0) or source install using GDAL and PROJ installed in what way? 
> It's useful to record ways in which installation on OSX has been accomplished.
> 
> Roger
> 
> 
> 
>> 
>>> sessionInfo()
>> R version 3.5.0 (2018-04-23)
>> Platform: x86_64-apple-darwin15.6.0 (64-bit)
>> Running under: macOS Sierra 10.12.6
>> 
>> Matrix products: default
>> BLAS: 
>> /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
>> LAPACK: 
>> /Library/Frameworks/R.framework/Versions/3.5/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] rgeos_0.3-28 rgdal_1.3-2  sp_1.3-1
>> 
>> loaded via a namespace (and not attached):
>> [1] compiler_3.5.0  tools_3.5.0 grid_3.5.0  lattice_0.20-35
>> 
>> Thanks for all you do!
>> 
>> Cheers,
>> Ben
>> 
>> 
>>> On Jun 11, 2018, at 3:53 AM, Roger Bivand  wrote:
>>> 
>>> On Mon, 11 Jun 2018, Gilles Benjamin Leduc wrote:
>>> 
>>>> Good monday!
>>>> 
>>>> I tried to update rgdal, I get a warning telling me the installation had a 
>>>> non-null exit status. I haven't cheak if it was working…
>>> 
>>> Thanks for responding - every user data point helps!
>>> 
>>> Could you please provide the output of sessionInfo(), and any error 
>>> messages you see on trying to update?
>>> 
>>> Roger
>>> 
>>>> 
>>>> Benjamin
>>>> 
>>>> 
>>>> Le Vendredi 8 Juin 2018 18:15 GMT, Roger Bivand  a 
>>>> écrit:
>>>> 
>>>>> There are new releases of sp, rgdal and rgeos on CRAN. Please install sp
>>>>> first, then the other two, which link to the installed sp. They all
>>>> 
>>>>> address so-called rchk issues, which have not so far been a problem, but
>>>>> might have become more fragile as R's internal memory management is made
>>>>> even more efficient. This involves compiled code using memory allocated by
>>>>> R to be freed by R's garbage collector, which has to know if an object is
>>>>> still being used. Tomas Kalibera, the author of rchk, helped resolve and
>>>>> explain the issues encountered - what was good coding practice fifteen
>>>>> years ago isn't always still good practice.
>>>>> 
>>>>> In addition, the earliest versions of GDAL and PROJ with which rgdal will
>>>>> work have been updated, and set to PROJ 4.8.0 and GDAL 1.11.4. The current
>>>>> released versions of PROJ and GDAL are to be prefered, as bugs have been
>>>>> fixed and new features and drivers introduced. A check has been put
>>>> 
>>>>> in place to trap attempts to install rgdal without a C++11-capable
>>>>> compiler when the GDAL version is >=2.3.0 - which requires C++11. rgeos is
>>>>> ready for the forthcoming version of GEOS.
>>>>> 
>>>>> The CRAN team has also been very supportive of our efforts to bring
>>>> 
>>>>> compiled code in these packages into rchk compliance.
>>>>> 
>>>>> Please get in touch if you see any loose ends in these releases.
>>>>> 
>>>>> Roger
>>>>> 
>>>>> --
>>>>> Roger Bivand
>>>>> Department of Economics, Norwegian School of Economics,
>>>>> Helleveien 30, N-5045 Bergen, Norway.
>>>>> voice: +47 55 95 93 55; e-mail: roger.biv...@nhh.no
>>>>> http://orcid.org/0000-0003-2392-6140
>>>>> https://scholar.google.no/citations?user=AWeghB0J=en
>>>>> 
>>>>> ___
>>>>> R-sig-Geo mailing list
>>>>> R-sig-Geo@r-project.org
>>>>> https://stat.ethz.ch/mailman/

Re: [R-sig-Geo] CRAN releases of sp, rgdal and rgeos

2018-06-11 Thread Ben Tupper
Hi,

I have been able to install all three without issue.  I have encountered no 
issues with usage.  

> sessionInfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: 
/Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
LAPACK: 
/Library/Frameworks/R.framework/Versions/3.5/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] rgeos_0.3-28 rgdal_1.3-2  sp_1.3-1

loaded via a namespace (and not attached):
[1] compiler_3.5.0  tools_3.5.0 grid_3.5.0  lattice_0.20-35

Thanks for all you do!

Cheers,
Ben


> On Jun 11, 2018, at 3:53 AM, Roger Bivand  wrote:
> 
> On Mon, 11 Jun 2018, Gilles Benjamin Leduc wrote:
> 
>> Good monday!
>> 
>> I tried to update rgdal, I get a warning telling me the installation had a 
>> non-null exit status. I haven't cheak if it was working…
> 
> Thanks for responding - every user data point helps!
> 
> Could you please provide the output of sessionInfo(), and any error messages 
> you see on trying to update?
> 
> Roger
> 
>> 
>> Benjamin
>> 
>> 
>> Le Vendredi 8 Juin 2018 18:15 GMT, Roger Bivand  a 
>> écrit:
>> 
>>> There are new releases of sp, rgdal and rgeos on CRAN. Please install sp
>>> first, then the other two, which link to the installed sp. They all
>> 
>>> address so-called rchk issues, which have not so far been a problem, but
>>> might have become more fragile as R's internal memory management is made
>>> even more efficient. This involves compiled code using memory allocated by
>>> R to be freed by R's garbage collector, which has to know if an object is
>>> still being used. Tomas Kalibera, the author of rchk, helped resolve and
>>> explain the issues encountered - what was good coding practice fifteen
>>> years ago isn't always still good practice.
>>> 
>>> In addition, the earliest versions of GDAL and PROJ with which rgdal will
>>> work have been updated, and set to PROJ 4.8.0 and GDAL 1.11.4. The current
>>> released versions of PROJ and GDAL are to be prefered, as bugs have been
>>> fixed and new features and drivers introduced. A check has been put
>> 
>>> in place to trap attempts to install rgdal without a C++11-capable
>>> compiler when the GDAL version is >=2.3.0 - which requires C++11. rgeos is
>>> ready for the forthcoming version of GEOS.
>>> 
>>> The CRAN team has also been very supportive of our efforts to bring
>> 
>>> compiled code in these packages into rchk compliance.
>>> 
>>> Please get in touch if you see any loose ends in these releases.
>>> 
>>> Roger
>>> 
>>> --
>>> Roger Bivand
>>> Department of Economics, Norwegian School of Economics,
>>> Helleveien 30, N-5045 Bergen, Norway.
>>> voice: +47 55 95 93 55; e-mail: roger.biv...@nhh.no
>>> http://orcid.org/-0003-2392-6140
>>> https://scholar.google.no/citations?user=AWeghB0J=en
>>> 
>>> ___
>>> R-sig-Geo mailing list
>>> R-sig-Geo@r-project.org
>>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>> 
>> 
>> 
>> 
>> 
> 
> -- 
> Roger Bivand
> Department of Economics, Norwegian School of Economics,
> Helleveien 30, N-5045 Bergen, Norway.
> voice: +47 55 95 93 55; e-mail: roger.biv...@nhh.no 
> <mailto:roger.biv...@nhh.no>
> http://orcid.org/-0003-2392-6140 <http://orcid.org/-0003-2392-6140>
> https://scholar.google.no/citations?user=AWeghB0J=en___
>  
> <https://scholar.google.no/citations?user=AWeghB0J=en___>
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org <mailto:R-sig-Geo@r-project.org>
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo 
> <https://stat.ethz.ch/mailman/listinfo/r-sig-geo>
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Extract xy coordinates from raster of interesting neighborhood cells

2018-05-30 Thread Ben Tupper
Hi,

I'm not sure why you expect 24 points - you have 4 locations and for each you 
want the 4 bishop's directions - so, I think at most you should expect 16 
points.  See http://www.lpc.uottawa.ca/publications/moransi/moran.htm 
<http://www.lpc.uottawa.ca/publications/moransi/moran.htm> for where I expect 4 
points for bishop's for each input location; perhaps you have a different idea 
of bishop's direction?  

Your second point [45.12069, -88.369745] is on to the southern edge of the 
raster - so it can't find points southward - only the 2 northward.

Finally, it may not make any difference at all, but your pts_s has no 
coordinate reference.  Below I show where I assign the same projection as your 
raster.  I also don't have 'land_mask' so I reused 'r' and used xyFromCell to 
backwards extract the adjacent cell coordinates.

Does that do the trick for you?

Cheers,
Ben

### START
require(raster)
require(sp)

## Create a raster
r <- raster(nc=30, nr=30)
r <- setValues(r, round(runif(ncell(r))* 255))
plot(r)

##Given interesting points coordinates
xd <- c( -24.99270,   45.12069,  99.40321,  73.64419)
yd <- c(-45.435267, -88.369745, -7.086949, 44.174530)
pts <- data.frame(xd,yd)
pts_s<- SpatialPoints(pts)
projection(pts_s) <- projection(r)
points(pts_s, col="red", pch=16)

## Find pixels center of each point 
N_cells <- cellFromXY(r, pts_s)

e <- adjacent(r, N_cells , directions='bishop', id=TRUE, sorted = TRUE)
xy <- xyFromCell(r, e[,'to'], spatial = TRUE)


#Visualization

plot(r)
points(pts_s, col="red", pch=16)
points(xy, col="black", pch=16)
### END





> On May 30, 2018, at 3:11 PM, ASANTOS via R-sig-Geo  
> wrote:
> 
> Dear R-Sig-Geo Members,
> 
> I've like to extract xy coordinates from raster of 24 neigborhood cells 
> that surround the 4 given points (pts_s) pixels and for this I used:
> 
> #Packages
> 
> require(raster)
> require(sp)
> 
> ## Create a raster
> r <- raster(nc=30, nr=30)
> r <- setValues(r, round(runif(ncell(r))* 255))
> plot(r)
> 
> ##Given interesting points coordinates
> xd <- c(-24.99270,45.12069,99.40321,73.64419)
> yd  <- c(-45.435267,-88.369745,-7.086949,44.174530)
> pts <- data.frame(xd,yd)
> pts_s<- SpatialPoints(pts)
> points(pts_s, col="red", pch=16)
> 
> ## Find pixels center of each point (My idea is not to use the original point 
> coordinates, but coordinates of the center of interesting pixel).
> N_cells <- cellFromXY(r, pts_s)
> 
> 
> # Extract xy coordinates from raster of 24 neighborhood cells given pixel 
> number N_cells
> e<-adjacent(r, N_cells , directions='bishop', id=TRUE)
> coordinates(land_mask)[e[,1],] ## Doesn't return 24 neighborhood by N_cells 
> object
> ng_coords<-coordinates(land_mask)[e[,1],]
> #
> 
> #Visualization
> 
> plot(r)
> points(pts_s, col="red", pch=16)
> points(ng_coords, col="black", pch=16)
> ##
> 
> But I don't have success because the ng_coords object is not a 24 
> neighborhood cells of each point that I search. There are solution for this?
> 
> Thanks in advance,
> 
> Alexandre
> 
> -- 
> ==
> Alexandre dos Santos
> Proteção Florestal
> IFMT - Instituto Federal de Educação, Ciência e Tecnologia de Mato Grosso
> Campus Cáceres
> Caixa Postal 244
> Avenida dos Ramires, s/n
> Bairro: Distrito Industrial
> Cáceres - MT  CEP: 78.200-000
> Fone: (+55) 65 99686-6970 (VIVO) (+55) 65 3221-2674 (FIXO)
> 
>alexandre.san...@cas.ifmt.edu.br
> Lattes: http://lattes.cnpq.br/1360403201088680
> OrcID: orcid.org/-0001-8232-6722
> Researchgate: www.researchgate.net/profile/Alexandre_Santos10
> LinkedIn: br.linkedin.com/in/alexandre-dos-santos-87961635
> Mendeley:www.mendeley.com/profiles/alexandre-dos-santos6/
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] raster::clump not working?

2018-05-25 Thread Ben Tupper
Hi,

I think it is actually correct - there is only one 'clump' of connected cells.  
In raster clumps are separated from other clumps by backgound (0 or NA).  In 
your example there is no background anywhere so there is just one clump. 

You can see the difference if you divide x in to halves with a row of NAs.  
Note that limited spatial extent so the clumping doesn't wrap around the globe 
which it will for [-180, 180].

r <- raster(ncols=36, nrows=18, xmn = 0, xmx = 36, ymn = 0, ymx = 18)
x <- init(r, fun='cell')
 
x[9,1:36] <- NA
y <- clump(x)
y
# class   : RasterLayer 
# dimensions  : 18, 36, 648  (nrow, ncol, ncell)
# resolution  : 1, 1  (x, y)
# extent  : 0, 36, 0, 18  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
# data source : in memory
# names   : clumps 
# values  : 1, 2  (min, max)

x[1:18, 18] <- NA
y
# class   : RasterLayer 
# dimensions  : 18, 36, 648  (nrow, ncol, ncell)
# resolution  : 1, 1  (x, y)
# extent  : 0, 36, 0, 18  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
# data source : in memory
# names   : clumps 
# values  : 1, 4  (min, max)


Cheers,
Ben


> On May 25, 2018, at 6:00 AM, João Carreiras <jmbcarrei...@gmail.com> wrote:
> 
> Hi!
> 
> I've been trying to run the clump command but the output is consistently a
> raster with values == 1. Please find below an example.
> 
> I'm sure I'm doing something stupid. However, the command is really
> straightforward and I can't seem to identify what the problem might be.
> 
> Any help really appreciated.
> Thanks
> Joao
> 
> r <- raster(ncols=36, nrows=18)
> x <- init(r, fun='cell')
> x
> class   : RasterLayer
> dimensions  : 18, 36, 648  (nrow, ncol, ncell)
> resolution  : 10, 10  (x, y)
> extent  : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
> coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
> data source : in memory
> names   : layer
> values  : 1, 648  (min, max)
> a <- clump(x)
> a
> class   : RasterLayer
> dimensions  : 18, 36, 648  (nrow, ncol, ncell)
> resolution  : 10, 10  (x, y)
> extent  : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
> coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
> data source : in memory
> names   : clumps
> values  : 1, 1  (min, max)
> 
> _______
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecological Forecasting: https://eco.bigelow.org/






[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Raster extract by polygon generating NAs

2018-05-16 Thread Ben Tupper
Hi,

It's hard to know without any reproducible code, but you will want to pay close 
attention to the value of the na.rm argument to 
raster::extract(Raster,SpatialPolygons)  

See ?extract for all the details.

Cheers,
Ben

> On May 16, 2018, at 2:27 PM, João Carreiras <jmbcarrei...@gmail.com> wrote:
> 
> Greetings!
> 
> I'm using the extract command (raster package) with a raster layer (x)
> and a spatial polygons dataframe (y). I'm using it to extract the sum
> of raster values by each spatial polygon. However, I'm getting NAs as
> a result for some polygon IDs, which I know isn't true because that
> doesn't happen in ArcGIS.
> 
> Does anyone experienced the same issue?
> 
> Thanks!
> Joao
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Tick Forecasting: https://eco.bigelow.org/





[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Substitute raster stack values based on matrix index

2018-04-10 Thread Ben Tupper
Hi,

I think you want to reform your lookup table into a 2 column matrix with 
columns from_value and to_value, and then use raster::reclassify()

The one thing that makes me hesitate is the lookup rule you describe.  If a 
cell has a value of 20 then assign lut value m[20,1]  So does that mean a cell 
value of 49 gets assigned  m[40,10] ?  What happens to a cell value of 3?  
These is no m[0,3].

Cheers,
Ben 


> On Apr 10, 2018, at 12:45 PM, Thiago V. dos Santos via R-sig-Geo 
> <r-sig-geo@r-project.org> wrote:
> 
> I have a large (7000x7000, 10-layered) raster stack whose values range from 0 
> to 100.
> 
> I need to modify the raster values using the a "lookup table" consisted of a 
> matrix which is 100 rows long by 10 cols wide, where the number of rows is 
> associated with the 0-100 value range of the raster and the number of columns 
> relates to the number of layers of the raster stack. 
> 
> The following code creates a toy example of my dataset:
> 
> # Create raster stackr <- raster(ncol=50, nrow=50)s <- stack(lapply(1:10, 
> function(x) setValues(r, 1:ncell(r
> 
> # Create lookup tablem <- matrix(sample(100, 100*10, TRUE), 100, 10)
> 
> Therefore, I need to loop through each cell of the raster and check its 
> value. For example, if the cell value is `20`, then the new value will be 
> reassigned from the 20th line and 1st column in the matrix.
> 
> And so on for the 2nd raster stack layer and 2nd matrix column. And so on for 
> the remaining raster stack layers and matrix columns.
> 
> Any ideas on how to do that?
> 
> I know this sounds a bit cumbersome, but that's how a few ISRIC-WISE's soil 
> datasets are organized!
> Greetings, -- Thiago V. dos Santos
> Postdoctoral Research FellowDepartment of Climate and Space Science and 
> EngineeringUniversity of Michigan
> 
>   [[alternative HTML version deleted]]
> 
> _______
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Tick Forecasting: https://eco.bigelow.org/





[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Change range of values of the legend

2018-02-09 Thread Ben Tupper
Hi,

Try 

plot(rast, zlim = c(-5, 5))

I think the zlim argument is passed through to graphics::image() via 
fields::image.plot() which raster::plot() calls.  I know it isn't super obvious 
until until you re-read the docs about 2000 times.

Cheers,
Ben 


> On Feb 9, 2018, at 9:39 AM, Stefano Sofia <stefano.so...@regione.marche.it> 
> wrote:
> 
> Dear list users,
> suppose that I have this simple raster:
> 
> library(raster)
> xy <- matrix(rnorm(400),20,20)
> rast <- raster(xy)
> 
> plot(rast) gives me a legend with range (-3,3).
> I would like to change the range of the legend to (-5,5), for example. I 
> tried with
> 
> plot(rast, legend=FALSE, axes=FALSE)
> r.range <- c(-5, 5)
> plot(rast, legend.only=TRUE, axis.args=list(at=seq(r.range[1], r.range[2], 
> 1), labels=seq(r.range[1], r.range[2], 1)))
> 
> but this does not expand the values of the legend.
> Could somebody give me some hints?
> 
> Thank you
> Stefano
> 
> 
> (oo)
> --oOO--( )--OOo
> Stefano Sofia PhD
> Area Meteorologica e  Area nivologica - Centro Funzionale
> Servizio Protezione Civile - Regione Marche
> Via del Colle Ameno 5
> 60126 Torrette di Ancona, Ancona
> Uff: 071 806 7743
> E-mail: stefano.so...@regione.marche.it
> ---Oo-oO
> 
> 
> 
> AVVISO IMPORTANTE: Questo messaggio di posta elettronica può contenere 
> informazioni confidenziali, pertanto è destinato solo a persone autorizzate 
> alla ricezione. I messaggi di posta elettronica per i client di Regione 
> Marche possono contenere informazioni confidenziali e con privilegi legali. 
> Se non si è il destinatario specificato, non leggere, copiare, inoltrare o 
> archiviare questo messaggio. Se si è ricevuto questo messaggio per errore, 
> inoltrarlo al mittente ed eliminarlo completamente dal sistema del proprio 
> computer. Ai sensi dell’art. 6 della DGR n. 1394/2008 si segnala che, in caso 
> di necessità ed urgenza, la risposta al presente messaggio di posta 
> elettronica può essere visionata da persone estranee al destinatario.
> IMPORTANT NOTICE: This e-mail message is intended to be received only by 
> persons entitled to receive the confidential information it may contain. 
> E-mail messages to clients of Regione Marche may contain information that is 
> confidential and legally privileged. Please do not read, copy, forward, or 
> store this message unless you are an intended recipient of it. If you have 
> received this message in error, please forward it to the sender and delete it 
> completely from your computer system.
> 
> --
> This message was scanned by Libra ESVA and is believed to be clean.
> 
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecocast Reports: http://seascapemodeling.org/ecocast.html
Tick Reports: https://report.bigelow.org/tick/
Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/




[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Reclassification of raster

2017-12-08 Thread Ben Tupper
Hi John,

I'm happy to help, but I have copied the r-sig-geo list as the community (and 
you and I) benefit from using the list.

I'm not very clear on what you mean by 'I loose the negative values'. Also, I 
don't see the connection between the raster you show and the quantile values 
computed.  If you asked for the 0% quantile you should get the lowest available 
value - (since all pixels are at or above this value).  According to the raster 
info you show that should be -0.893809, but instead your 0% quantile is shown 
to be 40.00199   Perhaps you have unwittingly mixed up the rasters you are 
using.

Here is what I get using a small reproducible example (thanks, reprex! 
https://github.com/tidyverse/reprex <https://github.com/tidyverse/reprex>)  You 
can see that all of the -1 values are classified to class #1.

library(raster)
#> Loading required package: sp

# make a dummy matrix that ranges from -1 to 6 
nx = 10
ny = 5
m <- matrix(sample(-1:6, nx*ny, replace = TRUE), nrow = nx, ncol = ny)

# and make a raster
r <- raster(m)
r
#> class   : RasterLayer 
#> dimensions  : 10, 5, 50  (nrow, ncol, ncell)
#> resolution  : 0.2, 0.1  (x, y)
#> extent  : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
#> coord. ref. : NA 
#> data source : in memory
#> names   : layer 
#> values  : -1, 6  (min, max)


# compute the quantiles
pp <- quantile(r, c(0, 0.15, 0.85))
pp
#>  0% 15% 85% 
#>  -1   0   5

# classify the pixels according to the quantile each pixel belongs to
ix <- findInterval(getValues(r), pp)

# make a classified version of r (class 0, 1 or 3)
classified_r <- setValues(r, ix) 
classified_r
#> class   : RasterLayer 
#> dimensions  : 10, 5, 50  (nrow, ncol, ncell)
#> resolution  : 0.2, 0.1  (x, y)
#> extent  : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
#> coord. ref. : NA 
#> data source : in memory
#> names   : layer 
#> values  : 1, 3  (min, max)

# show how they pair up
df <- data.frame(value = getValues(r), class = getValues(classified_r))
df
#>value class
#> 1  0 2
#> 2  0 2
#> 3  5 2
#> 4  6 3
#> 5  5 2
#> 6  4 2
#> 7  1 2
#> 8  5 2
#> 9 -1 1
#> 10 2 2
#> 11 0 2
#> 12 1 2
#> 13 3 2
#> 14 3 2
#> 15 6 3
#> 16-1 1
#> 17 2 2
#> 18 6 3
#> 19 1 2
#> 20 0 2
#> 21 1 2
#> 22 5 2
#> 23 4 2
#> 24 2 2
#> 25 1 2
#> 26 0 2
#> 27 4 2
#> 28 6 3
#> 29 3 2
#> 30 0 2
#> 31 6 3
#> 32 6 3
#> 33 0 2
#> 34 2 2
#> 35 2 2
#> 36 6 3
#> 37 5 2
#> 38 6 3
#> 39 1 2
#> 40 5 2
#> 41 4 2
#> 42 4 2
#> 43 3 2
#> 44 4 2
#> 45 0 2
#> 46 4 2
#> 47 0 2
#> 48 1 2
#> 49 1 2
#> 50-1 1


Cheers,
Ben


> On Dec 8, 2017, at 7:36 AM, John Wasige <johnwas...@gmail.com> wrote:
> 
> Hi Ben,
> 
> We had an email exchange on r-sig-geo@r-project.org 
> <mailto:r-sig-geo@r-project.org> in June this year on raster classification 
> where you made some suggestions. See the link below
> 
>  
> <http://r-sig-geo.2731867.n2.nabble.com/Thresholds-amp-reclassify-raster-td7591266.html>
> 
>  
> <http://r-sig-geo.2731867.n2.nabble.com/Thresholds-amp-reclassify-raster-td7591266.html>
> http://r-sig-geo.2731867.n2.nabble.com/Thresholds-amp-reclassify-raster-td7591266.html
>  
> <http://r-sig-geo.2731867.n2.nabble.com/Thresholds-amp-reclassify-raster-td7591266.html>
> 
>  
> <http://r-sig-geo.2731867.n2.nabble.com/Thresholds-amp-reclassify-raster-td7591266.html>
> However, when I run the reclassification, I loose the negative values. Any 
> suggestion on how I can have all data classified & not loose pixels?
> Thanks for your help
> 
> pp <- quantile(r, c(0, 0.15, 0.85)) 
> # pp 
> #   0%  15%  85% 
> # 40.00199 47.64569 82.50751 
> ix <- findInterval(getValues(r), pp) 
> classified_r <- setValues(r, ix) 
> 
> 
> 
> My raster looks;
> 
> class   : RasterLayer 
> dimensions  : 6557, 4281, 28070517  (nrow, ncol, ncell)
> resolution  : 0.0002335903, 0.0001525088  (x, y)
> extent  : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
> coord. ref. : NA 
> data source : J:\LPD_data\gpp.tif 
> names   : gpp 
> values  : -0.893809, 5.855252  (min, max)
> 
> 
>  
> <http://r-sig-geo.2731867.n2.nabble.com/Thresholds-amp-reclassify-raster-td7591266.html>
> 
>  
>

Re: [R-sig-Geo] make a raster from Aquarius files

2017-12-01 Thread Ben Tupper
Hi,

Those Aquarius files look quite different from others I have used from OBPG 
(mostly MODISA and SeaWiFS). 

As a short-cut alternative, you could read all of the values into a matrix and 
make a global raster from that.  An example is shown below.  You can also 
subset the extraction as you have shown, but it might be easier to subset after 
making the raster using raster::crop()

CHeers,
Ben


### START

library(raster)
library(ncdf4)
library(rasterVis)

filename = "Q20151522015181.L3m_MO_SCIA_V5.0_SSS_1deg"

nc = ncdf4::nc_open(filename)
m = ncdf4::ncvar_get(nc, 'l3m_data')
ncdf4::nc_close(nc)
r = raster::raster(t(m))
rasterVis::levelplot(r)

### END

> On Dec 1, 2017, at 6:24 AM, Michael Sumner <mdsum...@gmail.com> wrote:
> 
> That file name does not correspond to the standard patterns used by the
> oceancolor site. All the L3m products from there are now (NetCDF 4.0) .nc
> and so will work fine with raster/ncdf4.  (Some years ago they were HDF4 -
> without an extension, as the shortcuts in the image thumbnails hints
> (SMI/HDF and BIN/HDF - SMI/L3m standard mapped image in your case).
> 
> I think you've got some other provider's version of a file, but there's not
> enough information here to know where you got it or what form it's in. I'm
> happy to look if you can point us to the source of
> Q20151522015181.L3m_MO_SCISM_V5.0_SSS_1deg.
> 
> But otherwise, can you share with us the output of
> 
> nc.data<-nc_open("Q20151522015181.L3m_MO_SCISM_V5.0_SSS_1deg")
> print(nc.data)
> 
> and if you're on a suitable system with HDF4 support a gdalinfo output of
> the file would be useful too.
> 
> Given that you can read it with ncdf4, and if it actually is NetCDF4 (not
> HDF4 or something else) you might help raster work with it by renaming it
> to "Q20151522015181.L3m_MO_SCISM_V5.0_SSS_1deg.nc" since (unlike GDAL and
> the NetCDF lib itself) raster uses explicit extension to dispatch to
> different format logic code, though it ultimately sends it down to rgdal to
> deal with if it can't recognize it - which is why I'm surprised you can't
> get it to work and ( I'm guessing wildly now):
> 
> Do you not have rgdal installed?
> 
> 
> What system are you on? Please use sessionInfo() to share details.
> 
> Cheers, Mike.
> On Fri, 1 Dec 2017, 06:14 Antonio Silva, <aolinto@gmail.com> wrote:
> 
>> Hello
>> 
>> Some time ago I prepared scripts to extract temperature data from Modis
>> Aqua files. It can be found at https://gist.github.com/aolinto
>> 
>> HDF files can be downloaded at https://oceancolor.gsfc.nasa.gov/cgi/l3
>> 
>> I got the Aquarius sea surface salinity smoothed file from June 2015.
>> 
>> I could open and read the file:
>> 
>> library(ncdf4)
>> library(raster)
>> 
>> nc.data<-nc_open("Q20151522015181.L3m_MO_SCISM_V5.0_SSS_1deg")
>> print(nc.data)
>> dim(ncvar_get(nc.data,"l3m_data"))
>> ncvar_get(nc.data,"l3m_data")[c(110:160),c(110:117)]
>> 
>> But I could not prepare a raster from it. I tryed many things as:
>> 
>> rst.data <-
>> raster("Q20151522015181.L3m_MO_SCISM_V5.0_SSS_1deg",varname="l3m_data")
>> Error in .local(.Object, ...) :
>>  `AQUARIUS/Q20151522015181.L3m_MO_SCISM_V5.0_SSS_1deg' not recognised as a
>> supported file format.
>> 
>> Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer",
>> :
>>  Cannot create a RasterLayer object from this file.
>> 
>> and variations with band and layer.
>> 
>> I would greatly appreciate any suggestions to solve this issue.
>> 
>> Thanks
>> 
>> --
>> Antônio Olinto Ávila da Silva
>> Fisheries Institute
>> São Paulo, Brasil
>> 
>>[[alternative HTML version deleted]]
>> 
>> ___________
>> R-sig-Geo mailing list
>> R-sig-Geo@r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 
> -- 
> Dr. Michael Sumner
> Software and Database Engineer
> Australian Antarctic Division
> 203 Channel Highway
> Kingston Tasmania 7050 Australia
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecocast Reports: http://seascapemodeling.org/ecocast.html
Tick Reports: https://report.bigelow.org/tick/
Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Re: [R-sig-Geo] Soil as predictor in SDM

2017-09-27 Thread Ben Tupper
Hi,

This is addressed briefly in section 4.2 of the dismo package vignette.

https://cran.r-project.org/web/packages/dismo/vignettes/sdm.pdf 
<https://cran.r-project.org/web/packages/dismo/vignettes/sdm.pdf>

Does that answer your question?

Ben

> On Sep 27, 2017, at 10:59 AM, Maurizio Marchi <mauriziomarch...@gmail.com> 
> wrote:
> 
> Dear R users,
> I would like to include soil as predictor in my model and in addition to
> climatic variables. Anyway I have some doubts concerning the usd of
> categorical values such as the format of my raster file. Actually, my soil
> type data are categorical codes, should these codes be described as
> categories prior to be used? Or shoul I reclassify my raster into numeric
> values? My main concern is if I would create directional influence and bias
> in the results.
> Thanks
> -- 
> Maurizio Marchi
> Skype ID: maurizioxyz
> linux user 552742
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecocast Reports: http://seascapemodeling.org/ecocast.html
Tick Reports: https://report.bigelow.org/tick/
Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/




[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] useR! spatial presentations

2017-08-22 Thread Ben Tupper
Mike Treglia's comment, "Spatial stuff in #rstats is moving so fast! tough to 
keep up... but a good problem I guess" is spot on. I feel like I need to wear a 
bicycle helmet, elbow and knee pads, a seat belt and maybe a few pillows 
strapped on every time I sit down with the stuff.


> On Aug 22, 2017, at 9:05 AM, Roger Bivand <roger.biv...@nhh.no> wrote:
> 
> Edzer spotted:
> 
> https://twitter.com/Geospex/status/899670406944231424
> 
> and I copied the link here - thanks to Geospex/anonymous ...
> 
> On Tue, 22 Aug 2017, Ben Tupper wrote:
> 
>> A gold mine!  Thanks for sharing these.
>> 
>> 
>>> On Aug 22, 2017, at 5:40 AM, Roger Bivand <roger.biv...@nhh.no> wrote:
>>> 
>>> A useful listing of video links fro useR! in Brussels on spatial topics:
>>> 
>>> https://gist.github.com/anonymous/3d5b56cb16526db96dcaa0a579980187
>>> 
>>> --
>>> Roger Bivand
>>> Department of Economics, Norwegian School of Economics,
>>> Helleveien 30, N-5045 Bergen, Norway.
>>> voice: +47 55 95 93 55; e-mail: roger.biv...@nhh.no
>>> Editor-in-Chief of The R Journal, https://journal.r-project.org/index.html
>>> http://orcid.org/-0003-2392-6140
>>> https://scholar.google.no/citations?user=AWeghB0J=en
>>> 
>>> ___
>>> R-sig-Geo mailing list
>>> R-sig-Geo@r-project.org
>>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>> 
>> Ben Tupper
>> Bigelow Laboratory for Ocean Sciences
>> 60 Bigelow Drive, P.O. Box 380
>> East Boothbay, Maine 04544
>> http://www.bigelow.org
>> 
>> Ecocast Reports: http://seascapemodeling.org/ecocast.html
>> Tick Reports: https://report.bigelow.org/tick/
>> Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/
>> 
>> 
>> 
>> 
> 
> -- 
> Roger Bivand
> Department of Economics, Norwegian School of Economics,
> Helleveien 30, N-5045 Bergen, Norway.
> voice: +47 55 95 93 55; e-mail: roger.biv...@nhh.no
> Editor-in-Chief of The R Journal, https://journal.r-project.org/index.html
> http://orcid.org/-0003-2392-6140
> https://scholar.google.no/citations?user=AWeghB0J=en

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecocast Reports: http://seascapemodeling.org/ecocast.html
Tick Reports: https://report.bigelow.org/tick/
Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] useR! spatial presentations

2017-08-22 Thread Ben Tupper
A gold mine!  Thanks for sharing these.


> On Aug 22, 2017, at 5:40 AM, Roger Bivand <roger.biv...@nhh.no> wrote:
> 
> A useful listing of video links fro useR! in Brussels on spatial topics:
> 
> https://gist.github.com/anonymous/3d5b56cb16526db96dcaa0a579980187
> 
> -- 
> Roger Bivand
> Department of Economics, Norwegian School of Economics,
> Helleveien 30, N-5045 Bergen, Norway.
> voice: +47 55 95 93 55; e-mail: roger.biv...@nhh.no
> Editor-in-Chief of The R Journal, https://journal.r-project.org/index.html
> http://orcid.org/-0003-2392-6140
> https://scholar.google.no/citations?user=AWeghB0J=en
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecocast Reports: http://seascapemodeling.org/ecocast.html
Tick Reports: https://report.bigelow.org/tick/
Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Error in basename(x) : path too long

2017-07-31 Thread Ben Tupper
Hi John,

Using a raster::stack() should the perfect solution for you; I work with very 
large raster stacks all of the time.  From the introductory vignette 
https://cran.r-project.org/web/packages/raster/vignettes/Raster.pdf

"A notable feature of the raster package is that it can work with raster
datasets that are stored on disk and are too large to be loaded into memory
(RAM). The package can work with large files because the objects it creates
from these files only contain information about the structure of the data, such
as the number of rows and columns, the spatial extent, and the filename, but it
does not attempt to read all the cell values in memory."

Have you tried something like...

library(raster)
S <- stack(vector_of_filenames)

Ben




> On Jul 31, 2017, at 5:19 AM, John Wasige <johnwas...@gmail.com> wrote:
> 
> Thank you Ben,
> I would like to generate annual sums & means for each year from a list 
> rasters (not stack or brick because of memory issues with R). For 15 years I 
> have 345 individual rasters and frequency of 23 per year. 
> 
> I will be very glad for an idea on how to do that.
> 
> Thanks
> 
> John
> 
> 
> 
> 
> 
> On Sat, Jul 29, 2017 at 5:37 PM, Ben Tupper <btup...@bigelow.org> wrote:
> Hi again,
> 
> A late thought - I'm still on the first cups of coffee.
> 
> It looks to me like you are iterating over a stack to select certain layers 
> to sum.  You could achieve the same outcome with possibly much less work.  
> The following example will create a sum of 24-layer blocks along a stack of 
> rasters.
> 
> # from https://gist.github.com/btupper/20879e0b46e5ed63d402d7cff424dbb7
> #' Split a vector into groups of MAX (or possibly fewer)
> #'
> #' @param v vector or list to split
> #' @param MAX numeric the maximum size per group
> #' @return a list of the vector split into groups
> split_vector <- function(v, MAX = 200){
> nv <- length(v)
> if (nv <= MAX) return(list('1' = v))
> split(v, findInterval(1:nv, seq(from = 1, to = nv, by = MAX)))
> }
> 
> 
> library(raster)
> 
> N <- 345
> n <- 24
> nc <- 4
> nr <- 3
> 
> R <- raster(matrix(runif(nc*nr), ncol = nc, nrow = nr))
> 
> RR <- stack(lapply(seq_len(N), function(i) R))
> 
> ix <- split_vector(seq_len(N), MAX = n)
> 
> SS <- lapply(ix, function(index) sum(RR[[index]]))
> 
> So, S[[1]], which looks like this...
> 
> $`1`
> class   : RasterLayer
> dimensions  : 3, 4, 12  (nrow, ncol, ncell)
> resolution  : 0.25, 0.333  (x, y)
> extent  : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
> coord. ref. : NA
> data source : in memory
> names   : layer
> values  : 0.9451534, 20.0503  (min, max)
> 
> ... is the sum of the first 24 layers of RR. SS[[2]] will be the sum of the 
> next 24, and so on.
> 
> Is that what you are trying to do?
> 
> Cheers,
> Ben
> 
> 
> 
> 
> > On Jul 29, 2017, at 7:56 AM, John Wasige <johnwas...@gmail.com> wrote:
> >
> > ​Dear all,
> >
> > I am running the script below & I get the following error:
> > Error in basename(x) : path too long
> > ​
> > What could be the problem?
> > Thanks for your help
> > John
> >
> > ​### Script​
> >
> > setwd("I:/Mauritius2001_2015")  # directory of data
> > newlist= read.csv('I:/Mauritius2001_2015/Mauritius.csv',header=F)
> >
> > refr <- raster(paste("I:/Mauritius2001_2015/",newlist[i,1],sep = ""))
> > refr[!is.na(refr)] <- 0
> > for(i in seq(1,345,by=23)){
> >  rsum <- refr
> >  for(p in 0:22){
> >r <- raster(paste("I:/Mauritius2001_2015/",newlist[i+p],sep = ""))
> >rsum <- rsum + r
> >  }
> >  #   rsum <- rsum
> >  writeRaster(rsum,
> > filename=paste("D:/Mauritius2001_2015/Annual/",substr(newlist[i],1,6),".tif",sep=''),
> > format="GTiff", overwrite=TRUE)
> > }
> >
> >   [[alternative HTML version deleted]]
> >
> > ___
> > R-sig-Geo mailing list
> > R-sig-Geo@r-project.org
> > https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 
> Ben Tupper
> Bigelow Laboratory for Ocean Sciences
> 60 Bigelow Drive, P.O. Box 380
> East Boothbay, Maine 04544
> http://www.bigelow.org
> 
> Ecocast Reports: http://seascapemodeling.org/ecocast.html
> Tick Reports: https://report.bigelow.org/tick/
> Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/
> 
> 
> 
> 
> 
> 
> -- 
> John Wasige
> "There are no REGRATES in LIFE, just lessons (Jennifer Aniston)”

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecocast Reports: http://seascapemodeling.org/ecocast.html
Tick Reports: https://report.bigelow.org/tick/
Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Re: [R-sig-Geo] Error in basename(x) : path too long

2017-07-29 Thread Ben Tupper
Hi again,

A late thought - I'm still on the first cups of coffee.

It looks to me like you are iterating over a stack to select certain layers to 
sum.  You could achieve the same outcome with possibly much less work.  The 
following example will create a sum of 24-layer blocks along a stack of 
rasters. 

# from https://gist.github.com/btupper/20879e0b46e5ed63d402d7cff424dbb7
#' Split a vector into groups of MAX (or possibly fewer)
#'
#' @param v vector or list to split
#' @param MAX numeric the maximum size per group
#' @return a list of the vector split into groups
split_vector <- function(v, MAX = 200){
nv <- length(v)
if (nv <= MAX) return(list('1' = v))
split(v, findInterval(1:nv, seq(from = 1, to = nv, by = MAX)))
}


library(raster)

N <- 345
n <- 24
nc <- 4
nr <- 3

R <- raster(matrix(runif(nc*nr), ncol = nc, nrow = nr))

RR <- stack(lapply(seq_len(N), function(i) R))

ix <- split_vector(seq_len(N), MAX = n)

SS <- lapply(ix, function(index) sum(RR[[index]]))

So, S[[1]], which looks like this...

$`1`
class   : RasterLayer 
dimensions  : 3, 4, 12  (nrow, ncol, ncell)
resolution  : 0.25, 0.333  (x, y)
extent  : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
data source : in memory
names   : layer 
values  : 0.9451534, 20.0503  (min, max)

... is the sum of the first 24 layers of RR. SS[[2]] will be the sum of the 
next 24, and so on.

Is that what you are trying to do?

Cheers,
Ben




> On Jul 29, 2017, at 7:56 AM, John Wasige <johnwas...@gmail.com> wrote:
> 
> ​Dear all,
> 
> I am running the script below & I get the following error:
> Error in basename(x) : path too long
> ​
> What could be the problem?
> Thanks for your help
> John
> 
> ​### Script​
> 
> setwd("I:/Mauritius2001_2015")  # directory of data
> newlist= read.csv('I:/Mauritius2001_2015/Mauritius.csv',header=F)
> 
> refr <- raster(paste("I:/Mauritius2001_2015/",newlist[i,1],sep = ""))
> refr[!is.na(refr)] <- 0
> for(i in seq(1,345,by=23)){
>  rsum <- refr
>  for(p in 0:22){
>r <- raster(paste("I:/Mauritius2001_2015/",newlist[i+p],sep = ""))
>rsum <- rsum + r
>  }
>  #   rsum <- rsum
>  writeRaster(rsum,
> filename=paste("D:/Mauritius2001_2015/Annual/",substr(newlist[i],1,6),".tif",sep=''),
> format="GTiff", overwrite=TRUE)
> }
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecocast Reports: http://seascapemodeling.org/ecocast.html
Tick Reports: https://report.bigelow.org/tick/
Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Re: [R-sig-Geo] Error in basename(x) : path too long

2017-07-29 Thread Ben Tupper
Hi,

It's not possible to know but I have a suspicion and a suggestion.

suspicion:  You are accessing the elements of the data frame "newlist" 
different ways ...

> refr <- raster(paste("I:/Mauritius2001_2015/",newlist[i,1],sep = ""))

and 

> r <- raster(paste("I:/Mauritius2001_2015/",newlist[i+p],sep = ""))

and 

> filename=paste("D:/Mauritius2001_2015/Annual/",substr(newlist[i],1,6),".tif",sep='')


The first likely works.  The latter two return the (i+p)'th and i'th columns 
each as a new data frame so the filenames may indeed be quite long.  So, it 
looks like you need to work on your data frame indexing. 

suggestion:  Instead of using paste() to make file paths I suggest that you 
give file.path() a try.  It works across all platforms and is easier than using 
paste.

CHeers,
Ben

> On Jul 29, 2017, at 7:56 AM, John Wasige <johnwas...@gmail.com> wrote:
> 
> ​Dear all,
> 
> I am running the script below & I get the following error:
> Error in basename(x) : path too long
> ​
> What could be the problem?
> Thanks for your help
> John
> 
> ​### Script​
> 
> setwd("I:/Mauritius2001_2015")  # directory of data
> newlist= read.csv('I:/Mauritius2001_2015/Mauritius.csv',header=F)
> 
> refr <- raster(paste("I:/Mauritius2001_2015/",newlist[i,1],sep = ""))
> refr[!is.na(refr)] <- 0
> for(i in seq(1,345,by=23)){
>  rsum <- refr
>  for(p in 0:22){
>r <- raster(paste("I:/Mauritius2001_2015/",newlist[i+p],sep = ""))
>rsum <- rsum + r
>  }
>  #   rsum <- rsum
>  writeRaster(rsum,
> filename=paste("D:/Mauritius2001_2015/Annual/",substr(newlist[i],1,6),".tif",sep=''),
> format="GTiff", overwrite=TRUE)
> }
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Ecocast Reports: http://seascapemodeling.org/ecocast.html
Tick Reports: https://report.bigelow.org/tick/
Jellyfish Reports: https://jellyfish.bigelow.org/jellyfish/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Re: [R-sig-Geo] raster - unrotate?

2017-07-20 Thread Ben Tupper
Ahoy!

My (current) solution is to user raster::merge().  Works a treat and fits my 
workflow nicely.  Since I am obtaining the raster data using OPeNDAP it is easy 
to get the two regions, rotate the extent of the eastern region, and then 
merge.  Below is a pseudo-example (that works!) as it crops a local file twice, 
once for each region, rather than using an OPeNDaP calls via 
`ncdf4::nccvar_get(start = blah, count = something)` to get the two regions.


### start

library(raster)
uri <- 
'https://oceandata.sci.gsfc.nasa.gov:443/opendap/MODISA/L3SMI/2016/001/A20160012016032.L3m_R32_SST_sst_9km.nc'
R <- raster::raster(uri, varname = 'sst')

R 
#class   : RasterLayer 
#dimensions  : 180, 360, 64800  (nrow, ncol, ncell)
#resolution  : 1, 1  (x, y)
#extent  : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
#data source : in memory
#names   : layer 
#values  : 1.482572e-05, 0.928  (min, max)

par(mfrow = c(2,1))
plot(R)
lines(c(180, 100, 100, 180), c(80,80,0,0))
lines(c(-180,-90,-90,-180), c(80,80,0,0))

# eastern section
eR <- raster::crop(R, c(100, 180, 0, 80))

# rotate the extent
eExtent <- raster::extent(eR)
raster::extent(eR) <- c(-260, -180, eExtent[3:4])

# western section
wR <- raster::crop(R, c(-180, -90, 0, 80))

# merge
newR <- raster::merge(eR, wR)
newR

plot(newR)

 end

Cheers,
Ben

> On Jun 22, 2017, at 7:26 PM, Michael Sumner <mdsum...@gmail.com> wrote:
> 
> 
> 
> 
> On Thu, 22 Jun 2017 at 21:28 Ben Tupper <btup...@bigelow.org> wrote:
> Hi,
> 
> Wow!  A treasure from the past!
> 
> Hmmm.   I see what you mean; it might be best to snip-clip-and-smush from the 
> native presentation.  We are testing out the performance of the dineof 
> function in the sinkr package 
> (https://github.com/marchtaylor/sinkr/blob/master/R/dineof.R) to interpolate 
> patchy chlorophyl data.  
> 
> Thanks for the tip!
> 
> 
> 
> For what it's worth, I'm happy to help, there's no one size fits all here. 
> The dateline is one of those "easy problems" that does not have a general fix 
> and will bite in many different contexts. :)
> 
> The best distillation of my tricks is in this project, but it does depend on 
> your workflow and the actual data in use. 
> 
> https://github.com/hypertidy/tabularaster
> 
> If you have performance issues raster's cell abstraction  will help, but they 
> are a bit old-school when it comes to multi-part geometries. (It's identical 
> to standard database indexing concepts as are all "spatial" optimization 
> tricks)
> 
> (I see a desperate need for a general API for this kind of problem so that we 
> can build tools from a general framework, which I'm working on - that's some 
> kind of excuse for why this and related projects are quite raw and 
> unfinished.)
> 
> Cheers, Mike.  
> 
> Cheers,
> Ben
> 
>> On Jun 22, 2017, at 4:46 AM, Michael Sumner <mdsum...@gmail.com> wrote:
>> 
>> 
>> It used to do the inverse, and I preserved a copy of the old behaviour here: 
>> 
>> https://github.com/AustralianAntarcticDivision/raadtools/blob/master/R/utils.R#L9
>> 
>> You're probably best to learn from how it approaches it rather than just use 
>> it, since it's not a general capability, just works for those very specific 
>> cases. 
>> 
>> I just tested it and it still seems to work fine, I used 
>> 
>> oceandata.sci.gsfc.nasa.gov/MODISA/Mapped/Monthly/9km/chlor/A20021822002212.L3m_MO_CHL_chlor_a_9km.nc
>>  
>> 
>> obtainable with 
>> 
>> https://oceandata.sci.gsfc.nasa.gov/cgi/getfile/A20021822002212.L3m_MO_CHL_chlor_a_9km.nc
>>  
>> 
>> If you're extracting points you might as well just convert them into the 
>> "Atlantic" range, but it's painful to get that right for polygons or lines 
>> (and very hard to generalize once you get it working anyway). 
>> 
>> For simple regions like the one you show I'd probably split it into two 
>> extents() and use those - but depends on your workflow, all these options 
>> are useful here and there. 
>> 
>> Cheers, Mike. 
>> 
>> 
>> On Thu, 22 Jun 2017 at 18:30 Ben Tupper <btup...@bigelow.org> wrote:
>> Hello,
>> 
>> We have rasters that span [-180, 180] from NASA's Ocean Color 
>> (https://oceancolor.gsfc.nasa.gov/)  datasets.  We are trying to extract a 
>> region that spans 100E to 90W, that is 100 to -90.  The region 'wraps' 
>> across the edges as shown by the plot at the address below.
>> 
>> https://dl.dropboxusercontent.com/u/8433654/sst.png
>> 
>> 
>> library(raster)
>> uri <- 
&g

Re: [R-sig-Geo] raster - unrotate?

2017-06-26 Thread Ben Tupper
Hi,

Thanks for the offer to help.  I have been redirected for the time being to 
other tasks, but I expect I'll be back to this in a few weeks.  I think I will 
try your archived rotate() as I'm starting with whole-earth coverage - nothing 
tricky.

You have been going really deep with tabularaster.  I have been folding 
tidyverse into my 'stuff' over the last few months, but I am on a relatively 
short leash resource-wise so the effort feels feeble.  Most of my work uses 
rasters and dismo https://cran.r-project.org/web/packages/dismo/index.html with 
only minor use of non-raster spatial data.  That might be my lame excuse for 
not diving into sf yet; that and I haven't seen examples I can ape for getting 
sf and raster to play together (well, until tabularaster). 

Thanks!
Ben

> On Jun 22, 2017, at 7:26 PM, Michael Sumner <mdsum...@gmail.com> wrote:
> 
> 
> 
> 
> On Thu, 22 Jun 2017 at 21:28 Ben Tupper <btup...@bigelow.org 
> <mailto:btup...@bigelow.org>> wrote:
> Hi,
> 
> Wow!  A treasure from the past!
> 
> Hmmm.   I see what you mean; it might be best to snip-clip-and-smush from the 
> native presentation.  We are testing out the performance of the dineof 
> function in the sinkr package 
> (https://github.com/marchtaylor/sinkr/blob/master/R/dineof.R 
> <https://github.com/marchtaylor/sinkr/blob/master/R/dineof.R>) to interpolate 
> patchy chlorophyl data.  
> 
> Thanks for the tip!
> 
> 
> 
> For what it's worth, I'm happy to help, there's no one size fits all here. 
> The dateline is one of those "easy problems" that does not have a general fix 
> and will bite in many different contexts. :)
> 
> The best distillation of my tricks is in this project, but it does depend on 
> your workflow and the actual data in use. 
> 
> https://github.com/hypertidy/tabularaster 
> <https://github.com/hypertidy/tabularaster>
> 
> If you have performance issues raster's cell abstraction  will help, but they 
> are a bit old-school when it comes to multi-part geometries. (It's identical 
> to standard database indexing concepts as are all "spatial" optimization 
> tricks)
> 
> (I see a desperate need for a general API for this kind of problem so that we 
> can build tools from a general framework, which I'm working on - that's some 
> kind of excuse for why this and related projects are quite raw and 
> unfinished.)
> 
> Cheers, Mike.  
> 
> Cheers,
> Ben
> 
>> On Jun 22, 2017, at 4:46 AM, Michael Sumner <mdsum...@gmail.com 
>> <mailto:mdsum...@gmail.com>> wrote:
>> 
>> 
>> It used to do the inverse, and I preserved a copy of the old behaviour here: 
>> 
>> https://github.com/AustralianAntarcticDivision/raadtools/blob/master/R/utils.R#L9
>>  
>> <https://github.com/AustralianAntarcticDivision/raadtools/blob/master/R/utils.R#L9>
>> 
>> You're probably best to learn from how it approaches it rather than just use 
>> it, since it's not a general capability, just works for those very specific 
>> cases. 
>> 
>> I just tested it and it still seems to work fine, I used 
>> 
>> oceandata.sci.gsfc.nasa.gov/MODISA/Mapped/Monthly/9km/chlor/A20021822002212.L3m_MO_CHL_chlor_a_9km.nc
>>  
>> <http://oceandata.sci.gsfc.nasa.gov/MODISA/Mapped/Monthly/9km/chlor/A20021822002212.L3m_MO_CHL_chlor_a_9km.nc>
>>  
>> 
>> obtainable with 
>> 
>> https://oceandata.sci.gsfc.nasa.gov/cgi/getfile/A20021822002212.L3m_MO_CHL_chlor_a_9km.nc
>>  
>> <https://oceandata.sci.gsfc.nasa.gov/cgi/getfile/A20021822002212.L3m_MO_CHL_chlor_a_9km.nc>
>>  
>> 
>> If you're extracting points you might as well just convert them into the 
>> "Atlantic" range, but it's painful to get that right for polygons or lines 
>> (and very hard to generalize once you get it working anyway). 
>> 
>> For simple regions like the one you show I'd probably split it into two 
>> extents() and use those - but depends on your workflow, all these options 
>> are useful here and there. 
>> 
>> Cheers, Mike. 
>> 
>> 
>> On Thu, 22 Jun 2017 at 18:30 Ben Tupper <btup...@bigelow.org 
>> <mailto:btup...@bigelow.org>> wrote:
>> Hello,
>> 
>> We have rasters that span [-180, 180] from NASA's Ocean Color 
>> (https://oceancolor.gsfc.nasa.gov/ <https://oceancolor.gsfc.nasa.gov/>)  
>> datasets.  We are trying to extract a region that spans 100E to 90W, that is 
>> 100 to -90.  The region 'wraps' across the edges as shown by the plot at the 
>> address below.
>> 
>> https://dl.dropboxusercontent.com/u/8433654/sst.png 
>> <https://dl.dropbox

Re: [R-sig-Geo] Thresholds & reclassify raster

2017-06-22 Thread Ben Tupper
Hi,

Your attachment didn't make it through.

I'm not sure about your first option, but your second can use a combination of 
quantile() and findInterval() to create a classified raster.  Perhaps like 
this...


library(raster)
r <- raster()
r <- setValues(r, runif(ncell(r), 40, 90))

pp <- quantile(r, c(0, 0.15, 0.85))
# pp
#   0%  15%  85% 
# 40.00199 47.64569 82.50751 

ix <- findInterval(getValues(r), pp)

classified_r <- setValues(r, ix)

# > r
# class   : RasterLayer 
# dimensions  : 180, 360, 64800  (nrow, ncol, ncell)
# resolution  : 1, 1  (x, y)
# extent  : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
# data source : in memory
# names   : layer 
# values  : 40.00199, 89.99892  (min, max)

# > classified_r
# class   : RasterLayer 
# dimensions  : 180, 360, 64800  (nrow, ncol, ncell)
# resolution  : 1, 1  (x, y)
# extent  : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
# data source : in memory
# names   : layer 
# values  : 1, 3  (min, max)


Cheers,
Ben
> On Jun 22, 2017, at 4:04 AM, John Wasige <johnwas...@gmail.com> wrote:
> 
> ​Dear all​
> ,
> I am requesting for your help to reclassify the gpp.tif (attached) raster
> in R. Not sure my script here is doing the right thing.
> 
> ​#Data structure​
> 
> class   : RasterBrick
> dimensions  : 1243, 1409, 1751387, 1  (nrow, ncol, ncell, nlayers)
> resolution  : 0.00225804, 0.00225804  (x, y)
> extent  : -25.53282, -22.35125, 14.54232, 17.34906  (xmin, xmax, ymin, 
> ymax)
> coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
> data source : L:\NDVI_WGS84\gpp.tif
> names   :gpp
> min values  : -0.2176632
> max values  :   2.989293
> 
> 
> ​###​
> 
> ​I want to ​
> use the statistical distribution of gpp.tif values set threshold for change
> assignment. The thresholds should be set by the following two
> ​ ​
> options:
> 
> (Option1) => use  mean and StD and assign all pixel values  < mean - StD as
> negative change (class 1) and all values  > mean + StD as positive
> change (class
> 3); all values in between would be assigned 'neutral' for the final
> tabulation (class2).
> 
> (option2) => what may come to almost the same result is to do the
> cumulative histogram of the calculated GPPproxy pixels and assign all
> pixels below the 15 percentile to negative change (class1) and all pixel
> above the 85 percentile to positive change (class3) and again the range in
> between (15 to 85 percentile) would be assigned neutral (class2).
> 
> #R script
> 
> # classification
> #Option1_mean_sd
> gpp <- brick('L:/NDVI_WGS84/gpp.tif')
> hist(as.matrix(GPP))
> plot(GPPproxy)
> m <- cellStats(gpp, 'mean')
> sd <- cellStats(gpp, 'sd')
> v <- m-sd
> gppnew <- gpp-v
> plot(gppnew)
> gppnew[gppnew>0] <- 3
> gppnew[gppnew<0] <- 1
> gppnew[gppnew==0] <- 2
> plot(gppnew)
> writeRaster(gppnew, filename=paste("L:/NDVI_WGS84/gppnew_mean_sd",sep=''),
> format="GTiff", overwrite=TRUE)
> 
> #Option2_percentile
> max<- cellStats(gpp, 'max')
> gppnew2 <-(gpp/max)*100
> min <- cellStats(gpp, 'min')
> m <- matrix(c(min, 15, 1,
>  15, 85, 2,
>  85, Inf, 3), ncol=3, byrow=TRUE)
> gppnew_percentile <- reclassify(gppnew2, m)
> 
> hist(as.matrix(gppnew_percentile))
> writeRaster(gppnew_percentile,
> filename=paste("L:/NDVI_WGS84/gppnew_percentile",sep=''),
> format="GTiff", overwrite=TRUE)
> plot(gppnew_percentile)
> 
> ​Thanks for your help
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo

[R-sig-Geo] raster - unrotate?

2017-06-22 Thread Ben Tupper
Hello,

We have rasters that span [-180, 180] from NASA's Ocean Color 
(https://oceancolor.gsfc.nasa.gov/)  datasets.  We are trying to extract a 
region that spans 100E to 90W, that is 100 to -90.  The region 'wraps' across 
the edges as shown by the plot at the address below.

https://dl.dropboxusercontent.com/u/8433654/sst.png


library(raster)
uri <- 
'https://oceandata.sci.gsfc.nasa.gov:443/opendap/MODISA/L3SMI/2016/001/A20160012016032.L3m_R32_SST_sst_9km.nc'
R <- raster::raster(uri, varname = 'sst')

R 
#class   : RasterLayer 
#dimensions  : 180, 360, 64800  (nrow, ncol, ncell)
#resolution  : 1, 1  (x, y)
#extent  : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
#data source : in memory
#names   : layer 
#values  : 1.482572e-05, 0.928  (min, max)

plot(R)
lines(c(180, 100, 100, 180), c(80,80,0,0))
lines(c(-180,-90,-90,-180), c(80,80,0,0))

I see that there is the nice raster::rotate() function to rotate raster 
coordinates from [0,360] to [-180,180]. That would make extracting the region 
super easy if the inverse were available.  Is there an equivalent way to 
implement the inverse or raster::rotate()?  I could dig into the source of 
raster::rotate() to see how to code one up, but I hate like heck to reinvent 
the wheel.

Thanks!
Ben


Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Same mask for two rasters, but obtaining different extents in R

2017-03-16 Thread Ben Tupper
Hi,

In the short term you could use raster::alignExtent() to get align bio5 to the 
the extent of lg5.  

I would also inspect the source of your data and compare it to your locally 
stored copy of it.  If they are different then it would be worthwhile to review 
the steps you used to download, manipulate and store it.

Cheers,
Ben 

 
> On Mar 15, 2017, at 1:21 PM, Vijay Ramesh via R-sig-Geo 
> <r-sig-geo@r-project.org> wrote:
> 
> I re-checked the original extent and here it is: This is data obtained from
> WorldClim.
> 
>> bio5
> class   : RasterLayer
> dimensions  : 3600, 8640, 31104000  (nrow, ncol, ncell)
> resolution  : 0.0417, 0.0417  (x, y)
> extent  : -180, 180, -60, *90.1 * (xmin, xmax, ymin, ymax) #This
> varies at the 6th decimal place.
> coord. ref. : +proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs
> data source : C:\Users\rameshv\Downloads\Climate
> Stability\Data_LGM_Present\Present\1_RawData\bio_5
> names   : bio_5
> values  : -86, 489  (min, max)
> attributes  :
>ID COUNT
> from: -86 1
> to  : 48938
> 
> 
>> lg5
> class   : RasterLayer
> dimensions  : 3600, 8640, 31104000  (nrow, ncol, ncell)
> resolution  : 0.0417, 0.0417  (x, y)
> extent  : -180, 180, -60, 90  (xmin, xmax, ymin, ymax)
> coord. ref. : +proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs
> data source : C:\Users\rameshv\Downloads\Climate
> Stability\Data_LGM_Present\LGM\1_RawData\cclgmbi5.tif
> names   : cclgmbi5
> values  : -204, 519  (min, max)
> 
> What do you suggest?
> 
> Also, any suggestions on aligning them before I crop them? I wouldn't want
> to projectRaster using one of the rasters, as that creates extra number of
> rows (when I coerce the raster to a Spatial Pixels Data Frame).
> 
> 
> 
> On Wed, Mar 15, 2017 at 1:13 PM, Sarah Goslee <sarah.gos...@gmail.com>
> wrote:
> 
>> The most likely explanation seems to me that the rasters were not
>> aligned before cropping, so they are not aligned after cropping.
>> 
>> Have you checked the original extent and resolution?
>> 
>> Sarah
>> 
>> On Tue, Mar 14, 2017 at 5:31 PM, Vijay Ramesh via R-sig-Geo
>> <r-sig-geo@r-project.org> wrote:
>>> I loaded a shapefile in R, and cropped and masked it with the same mask,
>>> but I get different extents. Any suggestions?
>>> 
>>> Code below:
>>> 
>>>library(raster)
>>>library(rgdal)
>>>library(GISTools)
>>>library(sp)
>>>library(maptools)
>>> 
>>>##Loading the first mask
>>>Mask <- readOGR("C:\\Users\\rameshv\\Downloads\\Climate
>>> Stability\\SPV_Mask\\mask.shp")
>>>proj4string(Mask) <- CRS("+init=epsg:4326")
>>> 
>>>#Loading the Rasters For Present and LGM and clipping them to the
>> right
>>> extent
>>>bio5 <- raster("C:\\Users\\rameshv\\Downloads\\Climate
>>> Stability\\Data_LGM_Present\\Present\\1_RawData\\bio_5")
>>>proj4string(bio5) <- CRS("+init=epsg:4326")
>>>lg5 <- raster("C:\\Users\\rameshv\\Downloads\\Climate
>>> Stability\\Data_LGM_Present\\LGM\\1_RawData\\cclgmbi5.tif")
>>>proj4string(lg5) <- CRS("+init=epsg:4326")
>>> 
>>>##Cropping by using the Crop and Mask functions
>>>cr<- crop(bio5, extent(Mask))
>>>bio5 <- mask(cr, Mask)
>>> 
>>>cr2<- crop(lg5, extent(Mask))
>>>lg5<- mask(cr2, Mask)
>>> 
>>>> bio5
>>> class   : RasterLayer
>>> dimensions  : 339, 246, 83394  (nrow, ncol, ncell)
>>> resolution  : 0.0417, 0.0417  (x, y)
>>> extent  : 72.45835, 82.70835, 8.083337, 22.20834  (xmin, xmax,
>>> ymin, ymax)
>>> coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs
>>> +ellps=WGS84 +towgs84=0,0,0
>>> data source : in memory
>>> names   : bio_5
>>> values  : 207, 432  (min, max)
>>> attributes  :
>>>ID COUNT
>>> from: -86 1
>>> to  : 48938
>>> 
>>>> lg5
>>> class   : RasterLayer
>>> dimensions  : 339, 246, 83394  (nrow, ncol, ncell)
>>> resolution  : 0.0417, 0.0417  (x, y)
>>> extent  : 72.45833, 82.70833, 8.083333, 22.20833  (xmin, xmax,
>>> ymin, ymax)
>>> coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 

Re: [R-sig-Geo] Same mask for two rasters, but obtaining different extents in R

2017-03-15 Thread Ben Tupper
Hi,

Might you show us what bio5 and lg5 look like before you do the masking?

Cheers,
Ben


> On Mar 14, 2017, at 5:31 PM, Vijay Ramesh via R-sig-Geo 
> <r-sig-geo@r-project.org> wrote:
> 
> I loaded a shapefile in R, and cropped and masked it with the same mask,
> but I get different extents. Any suggestions?
> 
> Code below:
> 
>library(raster)
>library(rgdal)
>library(GISTools)
>library(sp)
>library(maptools)
> 
>##Loading the first mask
>Mask <- readOGR("C:\\Users\\rameshv\\Downloads\\Climate
> Stability\\SPV_Mask\\mask.shp")
>proj4string(Mask) <- CRS("+init=epsg:4326")
> 
>#Loading the Rasters For Present and LGM and clipping them to the right
> extent
>bio5 <- raster("C:\\Users\\rameshv\\Downloads\\Climate
> Stability\\Data_LGM_Present\\Present\\1_RawData\\bio_5")
>proj4string(bio5) <- CRS("+init=epsg:4326")
>lg5 <- raster("C:\\Users\\rameshv\\Downloads\\Climate
> Stability\\Data_LGM_Present\\LGM\\1_RawData\\cclgmbi5.tif")
>proj4string(lg5) <- CRS("+init=epsg:4326")
> 
>##Cropping by using the Crop and Mask functions
>cr<- crop(bio5, extent(Mask))
>bio5 <- mask(cr, Mask)
> 
>cr2<- crop(lg5, extent(Mask))
>lg5<- mask(cr2, Mask)
> 
>> bio5
> class   : RasterLayer
> dimensions  : 339, 246, 83394  (nrow, ncol, ncell)
> resolution  : 0.0417, 0.0417  (x, y)
> extent  : 72.45835, 82.70835, 8.083337, 22.20834  (xmin, xmax,
> ymin, ymax)
> coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs
> +ellps=WGS84 +towgs84=0,0,0
> data source : in memory
> names   : bio_5
> values  : 207, 432  (min, max)
> attributes  :
>ID COUNT
> from: -86 1
> to  : 48938
> 
>> lg5
> class   : RasterLayer
> dimensions  : 339, 246, 83394  (nrow, ncol, ncell)
> resolution  : 0.0417, 0.0417  (x, y)
> extent  : 72.45833, 82.70833, 8.08, 22.20833  (xmin, xmax,
> ymin, ymax)
> coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs
> +ellps=WGS84 +towgs84=0,0,0
> data source : in memory
> names   : cclgmbi5
> values  : 187, 392  (min, max)
> 
> 
> -- 
> Data Manager,
> Barbara Han Lab,
> Cary Institute of Ecosystem Studies,
> 2801 Sharon Turnpike, Millbrook, NY 12545
> Lab Site : http://www.hanlab.science/
> Personal Site : http://evolecol.weebly.com/
> Phone : (845)-677-7600 Ext: 241
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Assign a unique ID number to each patch in a raster

2017-01-26 Thread Ben Tupper
Hi,

I think you are asking for connected component labeling. raster::clump() 
expects your features to be like islands surrounded by NA or 0 background. 
There might be more Raster* centric ways to do it, but you could use plain old 
vanilla image processing using the very good imager package ( 
https://cran.r-project.org/web/packages/imager/ 
<https://cran.r-project.org/web/packages/imager/> ).  The steps below show in 
color your actual values with the connected component IDs labeled on each cell. 
 I used the 8-connected labeling but 4-connected is also available.

library(raster)
library(imager)

set.seed(10)
nc <- 8
nr <- 8
MIN <- 1
MAX <- 4
LUT <- c("orange", "green", "darkgoldenrod", "cornflowerblue")

r <- raster(ncols=nc, nrows=nr)
r[] <- round(runif(ncell(r),MIN, MAX),digits=0)
cc <- r

img <- imager::as.cimg(as.matrix(r))
labeled <- imager::label(img, high_connectivity = TRUE)
cc[] <- as.matrix(labeled)

plot(r, col = LUT)
txt <- cc[]
xy <- raster::xyFromCell(cc, 1:raster::ncell(cc))
text(xy[,1], xy[,2], txt )


Cheers,
Ben 
> On Jan 26, 2017, at 4:48 PM, Nelly Reduan <nell.r...@hotmail.fr> wrote:
> 
> Hello,
> I would like to assign a unique ID number to each patch (a patch is composed 
> of a set of adjacent cells) as shown in this figure:
>  <2328.png>
> 
> I tested the clump function (package raster) by applying an eight adjacent 
> cells rule but this function mixes all cell values into single patch. 
> 
> Here is a code example to create a raster. The raster contains values ranged 
> from 1 to 9.
> r <- raster(ncols=12, nrows=12)
> r[] <- round(runif(ncell(r),1,9),digits=0)
> plot(r)
> 
> Is there a way to assign a unique ID number to grouping cells that form a 
> patch for each class (i.e., values 1, 2, 3, 4, 5, 6, 7, 8, 9) ?
> 
> Thanks a lot for your time
> Nell
> 
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org <mailto:R-sig-Geo@r-project.org>
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo 
> <https://stat.ethz.ch/mailman/listinfo/r-sig-geo>
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org




[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Converting raster to a matrix

2017-01-24 Thread Ben Tupper
Hi,

It doesn't seem to be noted in the documentation for raster::raster(), but when 
you create a RasterLayer from a RasterLayer,  as in your

> rast <-  raster(image)

step, the values are stripped from the resulting RasterLayer.  Why don't you 
eliminate that step and retrieve the matrix from your first RasterLayer?

> mat <- as.matrix(image)
> str(mat)
 int [1:68, 1:65] NA NA NA NA NA NA NA NA NA NA ...

Ben




> On Jan 24, 2017, at 3:23 AM, John Wasige <johnwas...@gmail.com> wrote:
> 
> ​Dear all,
> Greetings!
> 
> I want to convert a big raster (see attached) a matrix, however, I get the 
> error below from the script. Anybody with an Idea on what is going wrong in 
> my script?
> 
> ###Errors at the following point in the script​
> 
> > mat <- as.matrix(rast)
> Error in .local(x, ...) : 'x' has no values
> 
> #script
> 
> 
> ​library(raster)
> library(rgdal)
> 
> setwd('D:/Mobile_testdata')
> image <- raster('D:/Mobile_testdata/SOSug_mean2qgis.tif')
> 
> rast <-  raster(image)
> mat <- as.matrix(rast)
> 
> Thanks for your help
> 
> Rgds John
> 
> _______
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org




[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Re: [R-sig-Geo] Passing a custom function to raster::focal

2017-01-10 Thread Ben Tupper
Hi,

Your calc_pctg() function is trying to treat the input as a raster (well, a 
mini-raster).  I think that you actually get a numeric.  So, if you drop the 
call to values(x) in the sum you should be fine.


# Function to calculate percentage of cells with value of 1
calc_pctg <- function(x)
{
 pct_val <- sum(x == 1, na.rm = TRUE)/length(x)
 return(pct_val)
}

Ben

 

> On Jan 10, 2017, at 9:59 AM, Mirza Cengic <mirzac...@gmail.com> wrote:
> 
> Hi all,
> 
> I want to run the focal() function from the raster package with a custom
> function. I want to calculate within a moving kernel (in the example I
> provided 5x5), what is the percentage of cells with the value 1 (frequency
> would work as well), and assign the value of the center cell of the moving
> window. The error occurs when I run the focal function. I suppose the error
> might come from using an inappropriate method on the object, but I am not
> really sure how to solve it. Could you please give me some hints what am I
> doing wrong.
> 
> 
> Regards,
> Mirza.
> 
> Example:
> 
> library(raster)
>> 
>> my_rast <- raster(ncols=40, nrows=20, xmn=0)
>> my_rast[] <- rnorm(ncell(my_rast))
>> 
>> # Reclassify to binary raster
>> my_mat <- c(cellStats(my_rast, min),cellStats(my_rast, max)/2,
>>   cellStats(my_rast, max)/2, cellStats(my_rast, max), 0,1)
>> my_rcl_mat <- matrix(my_mat, ncol=3, byrow=FALSE)
>> my_rast_rcl <- reclassify(my_rast, my_rcl_mat)
>> 
>> # Function to calculate percentage of cells with value of 1
>> calc_pctg <- function(x)
>> {
>>  pct_val <- sum(values(x) == 1, na.rm = TRUE)/length(x)
>>  return(pct_val)
>> }
>> 
>> # Run focal
>> my_rast_fcl <- focal(my_rast_rcl,
>> w = matrix(1/25,nrow=5,ncol=5),
>> calc_pctg)
> 
> 
> 
> 
> 
>> 
> 
> -- 
>> 
> *Mirza Čengić*
> 
> *Junior Researcher | Department of Environmental Science*
> Radboud University | Heyendaalseweg 135
> 6525 AJ Nijmegen | The Netherlands
> 
> +31 657020823 | +38761908392
> Skype: mirzacengic
> <https://www.linkedin.com/in/mirzacengic>
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Re: [R-sig-Geo] rasterVis::streamplot with colorkey

2016-12-23 Thread Ben Tupper
Hi,

Thanks so much for the tips!

Today the package author has kindly added a colorkey argument to streamplot 
function with a FALSE default value.  Setting it to TRUE draws the colorkey.  
Whooo!

https://github.com/oscarperpinan/rastervis/commit/ea1c49e945616e8c7dc203069dbc2a1e2d91baf7

Cheers,
ben


> On Dec 23, 2016, at 7:36 AM, chris english <englishchristoph...@gmail.com> 
> wrote:
> 
> Ben,
> 
> Not so much hard wired (colorkey) but coming in a couple of times so which to 
> use? As kind of explained here:
> http://stackoverflow.com/questions/34320868/map-with-panel-plots 
> <http://stackoverflow.com/questions/34320868/map-with-panel-plots>,
> 
> and further, more directly on rasterVis from Augustin Lobo:
> http://rpubs.com/alobo/rasterVis_Intro1 
> <http://rpubs.com/alobo/rasterVis_Intro1>
> 
> which looks like it will get you to the results you want, though I haven't 
> worked it through your example.
> HTH,
> Chris
> 
> 
> 
> On Wed, Dec 21, 2016 at 11:14 AM, Ben Tupper <btup...@bigelow.org 
> <mailto:btup...@bigelow.org>> wrote:
> Hello,
> 
> We have wind data that we would like to draw with rasterVis::streamplot(). We 
> would like to include a colorkey to associate with the region but it seems 
> that deep down rasterVis::streamplot has hardwired `colorkey = FALSE`  I'm 
> not sure how to circumvent this to allow for a color key. So, in brief...
> 
> How do I draw a streamplot with a colorkey?
> 
> Below is my example and sessionInfo() output.
> 
> Thanks so much,
> Ben
> 
> ### begin example
> library(raster)
> library(rasterVis)
> library(RColorBrewer)
> 
> V = volcano/10
> V = V - mean(V)
> U = V[nrow(V):1,]
> 
> V = raster::raster(V)
> U = raster::raster(U)
> S = raster::stack(U,V)
> 
> rasterVis::streamplot(S,
> isField = 'dXY',
> par.settings = rasterVis::streamTheme(
> region = rev(RColorBrewer::brewer.pal(n=4, name= 'Greys')),
> symbol = hexbin::BTC(n=9,beg=20)),
> droplet = list(pc = 1),
> scales = list(draw = TRUE),
> colorkey = TRUE)
> 
> # Error in .local(x, data, ...) :
> #  formal argument "colorkey" matched by multiple actual arguments
> 
> ### end example
> 
> 
> > sessionInfo()
> R version 3.3.1 (2016-06-21)
> Platform: x86_64-apple-darwin13.4.0 (64-bit)
> Running under: OS X 10.11.6 (El Capitan)
> 
> 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] rasterVis_0.40      latticeExtra_0.6-28 RColorBrewer_1.1-2  
> lattice_0.20-33 raster_2.5-8sp_1.2-3
> 
> loaded via a namespace (and not attached):
> [1] zoo_1.7-13parallel_3.3.1hexbin_1.27.1 Rcpp_0.12.6   
> grid_3.3.1viridisLite_0.1.3
> 
> 
> 
> 
> 
> Ben Tupper
> Bigelow Laboratory for Ocean Sciences
> 60 Bigelow Drive, P.O. Box 380
> East Boothbay, Maine 04544
> http://www.bigelow.org <http://www.bigelow.org/>
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org <mailto:R-sig-Geo@r-project.org>
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo 
> <https://stat.ethz.ch/mailman/listinfo/r-sig-geo>
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org




[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


[R-sig-Geo] rasterVis::streamplot with colorkey

2016-12-21 Thread Ben Tupper
Hello,

We have wind data that we would like to draw with rasterVis::streamplot(). We 
would like to include a colorkey to associate with the region but it seems that 
deep down rasterVis::streamplot has hardwired `colorkey = FALSE`  I'm not sure 
how to circumvent this to allow for a color key. So, in brief...  

How do I draw a streamplot with a colorkey?

Below is my example and sessionInfo() output.

Thanks so much,
Ben

### begin example
library(raster)
library(rasterVis)
library(RColorBrewer)

V = volcano/10
V = V - mean(V)
U = V[nrow(V):1,]

V = raster::raster(V)
U = raster::raster(U)
S = raster::stack(U,V)

rasterVis::streamplot(S,
isField = 'dXY',
par.settings = rasterVis::streamTheme(
region = rev(RColorBrewer::brewer.pal(n=4, name= 'Greys')),
symbol = hexbin::BTC(n=9,beg=20)),
droplet = list(pc = 1),
scales = list(draw = TRUE),
colorkey = TRUE) 

# Error in .local(x, data, ...) : 
#  formal argument "colorkey" matched by multiple actual arguments

### end example


> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.6 (El Capitan)

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] rasterVis_0.40  latticeExtra_0.6-28 RColorBrewer_1.1-2  lattice_0.20-33 
raster_2.5-8sp_1.2-3   

loaded via a namespace (and not attached):
[1] zoo_1.7-13parallel_3.3.1hexbin_1.27.1 Rcpp_0.12.6   
grid_3.3.1viridisLite_0.1.3





Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] GLOBE DEM in R?

2016-11-09 Thread Ben Tupper
Hi,

You might give the Natural Earth topography a shake...

https://github.com/BigelowLab/nearth

I don't know how it compares to the ETOPO datasets.

Cheers,
Ben

> On Nov 9, 2016, at 7:02 PM, Michael Sumner <mdsum...@gmail.com> wrote:
> 
> The only available global DEM in an R package that I know is geomapdata
> which has Etopo5 (or equivalent) in it.
> 
> Otherwise there is marmap with getNOAA.bathy() function, and I would look
> at xtractomatic as well for access to online services.
> 
> I tend to keep Etopo1, Etopo2, GEBCO14, and a bunch of other non-global
> ones in local files since we use them intensively, and happy to help if you
> need guidance with any of those.
> 
> There is IBCSO in polar form the southern hemisphere, but not sure if
> there's an equivalent for the north?
> 
> Generally I go for the NetCDF version (either .nc or .grd) now that ncdf4
> is fully supported by CRAN, otherwise use GeoTIFF if they provide it.
> Sometimes need some augmentation when reading with raster() to make sure
> things are interpreted fully/perfectly, but mostly it's pretty good.
> 
> If there are other sources I'm keen to hear as well.
> 
> Cheers, Mike.
> 
> 
> 
> On Thu, 10 Nov 2016 at 09:08 Andy Bunn <andy.b...@wwu.edu> wrote:
> 
>> Is the GLOBE DEM accessible in R via a package? I usually use
>> raster::getData() when I need elev data but I need to sample a SPDF of a
>> few thousand points with latitudes higher than the SRTM covers. Thoughts
>> appreciated.
>> 
>> -Andy
>> 
>> 
>>[[alternative HTML version deleted]]
>> 
>> ___
>> R-sig-Geo mailing list
>> R-sig-Geo@r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>> 
> -- 
> Dr. Michael Sumner
> Software and Database Engineer
> Australian Antarctic Division
> 203 Channel Highway
> Kingston Tasmania 7050 Australia
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] rasterVis, multiple plots and scalebar labels

2016-09-24 Thread Ben Tupper
Yes!  That's exactly what I am looking for.

Thanks and cheers,
Ben

> On Sep 24, 2016, at 3:59 AM, Tim Appelhans <tim.appelh...@gmail.com> wrote:
> 
> Is this producing what you want?
> 
> rasterVis::levelplot(xx, colorkey = list(at = at, labels = labels))
> 
> colorkey takes a list of arguments, including at and labels. This way it can 
> be differentiated from the at passed to levelplot itself.
> 
> Tim
> 
> On 24.09.2016 02:59, Ben Tupper wrote:
>> Hi Melanie,
>> 
>> Thanks for this.  I tried that approach by adding layers with the 
>> latticeExtra package - no joy yet.  My lattice skills are a bit wobbly - but 
>> I have The Good Books in hand so I'll keep noodling around and may prevail 
>> yet.
>> 
>> https://www.r-project.org/doc/bib/R-books_bib.html#R:Sarkar:2008
>> https://www.r-project.org/doc/bib/R-books_bib.html#R:Bivand+Pebesma+Gomez-Rubio:2008
>> http://oscarperpinan.github.io/spacetime-vis/
>> 
>> Cheers,
>> Ben
>> 
>>> On Sep 23, 2016, at 12:55 PM, Bacou, Melanie <m...@mbacou.com> wrote:
>>> 
>>> Here is a stump that might also work with levelplot():
>>> 
>>> # Plot raster with no scalebar first
>>> raster::plot(r, col=vector_of_colors, legend=FALSE, axes=FALSE)
>>> 
>>> # Add a custom scalebar
>>> raster::plot(r, legend.only=TRUE,
>>>  col=vector_of_colors,
>>>  axis.args=list(at=1:length(vector_of_labels), labels=vector_of_labels)
>>> 
>>> 
>>> On 9/23/2016 12:11 PM, Ben Tupper wrote:
>>>> Hi,
>>>> 
>>>> I would like to specify the labels drawn on the scalebar for a 
>>>> multi-raster plot.  I have seen this exchange (and try to replicate for 
>>>> multiple rasters below)
>>>> 
>>>> https://stat.ethz.ch/pipermail/r-help/2011-August/286705.html
>>>> 
>>>> I can't make that work with rasterVis::levelplot()
>>>> 
>>>> # start preparatory
>>>> library(raster)
>>>> library(rasterVis)
>>>> 
>>>> x <- raster::raster(volcano,
>>>>crs = '+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0',
>>>>xmn = -45, xmx = -40, ymn = 39, ymx = 47)
>>>> xx <- addLayer(x,x,x)
>>>> 
>>>> at <- seq(90, 200, length = 10)
>>>> labels <- rep(" ", length(at))
>>>> labels[1] <- "low"
>>>> labels[length(labels)] <- "high"
>>>> # end preparatory
>>>> 
>>>> # try as in help exchange above - ticks are labeled with numerics
>>>> rasterVis::levelplot(xx,
>>>>  colorkey = list(at = at),
>>>>  labels = list(labels = labels, at = at) )
>>>> 
>>>> # try as described in ?rasterVis::levelplot section for labels
>>>> # ticks still labeled with numerics
>>>> rasterVis::levelplot(xx,
>>>>at = at,
>>>>labels = labels )
>>>> 
>>>> I'm stumped!  How do I control the tick labels on a scalebar?
>>>> 
>>>> Thanks!
>>>> Ben
>>>> 
>>>> 
>>>>> sessionInfo()
>>>> R version 3.3.1 (2016-06-21)
>>>> Platform: x86_64-apple-darwin13.4.0 (64-bit)
>>>> Running under: OS X 10.11.6 (El Capitan)
>>>> 
>>>> 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] rasterVis_0.40  latticeExtra_0.6-28 RColorBrewer_1.1-2  
>>>> lattice_0.20-33
>>>> [5] raster_2.5-8sp_1.2-3
>>>> 
>>>> loaded via a namespace (and not attached):
>>>> [1] zoo_1.7-13rgdal_1.1-10  parallel_3.3.1hexbin_1.27.1
>>>> [5] Rcpp_0.12.6   grid_3.3.1viridisLite_0.1.3
>>>> 
>>>> 
>>>> Ben Tupper
>>>> Bigelow Laboratory for Ocean Sciences
>>>> 60 Bigelow Drive, P.O. Box 380
>>>> East Boothbay, Maine 04544
>>>> http://www.bigelow.org
>>>> 
>>>> ___
>>>> R-sig-Geo mailing list
>>>> R-sig-Geo@r-project.org
>>>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>> Ben Tupper
>> Bigelow Laboratory for Ocean Sciences
>> 60 Bigelow Drive, P.O. Box 380
>> East Boothbay, Maine 04544
>> http://www.bigelow.org
>> 
>> ___
>> R-sig-Geo mailing list
>> R-sig-Geo@r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 
> -- 
> #
> Tim Appelhans
> Department of Geography
> Environmental Informatics
> Philipps Universität Marburg
> Deutschhausstraße 12
> Raum 00A08
> 35032 Marburg (Paketpost: 35037 Marburg)
> Germany
> 
> Tel +49 (0) 6421 28-25957
> 
> http://environmentalinformatics-marburg.de/
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] rasterVis, multiple plots and scalebar labels

2016-09-23 Thread Ben Tupper
Hi Melanie,

Thanks for this.  I tried that approach by adding layers with the latticeExtra 
package - no joy yet.  My lattice skills are a bit wobbly - but I have The Good 
Books in hand so I'll keep noodling around and may prevail yet.

https://www.r-project.org/doc/bib/R-books_bib.html#R:Sarkar:2008
https://www.r-project.org/doc/bib/R-books_bib.html#R:Bivand+Pebesma+Gomez-Rubio:2008
http://oscarperpinan.github.io/spacetime-vis/

Cheers,
Ben

> On Sep 23, 2016, at 12:55 PM, Bacou, Melanie <m...@mbacou.com> wrote:
> 
> Here is a stump that might also work with levelplot():
> 
> # Plot raster with no scalebar first
> raster::plot(r, col=vector_of_colors, legend=FALSE, axes=FALSE)
> 
> # Add a custom scalebar
> raster::plot(r, legend.only=TRUE,
>  col=vector_of_colors,
>  axis.args=list(at=1:length(vector_of_labels), labels=vector_of_labels)
> 
> 
> On 9/23/2016 12:11 PM, Ben Tupper wrote:
>> Hi,
>> 
>> I would like to specify the labels drawn on the scalebar for a multi-raster 
>> plot.  I have seen this exchange (and try to replicate for multiple rasters 
>> below)
>> 
>> https://stat.ethz.ch/pipermail/r-help/2011-August/286705.html
>> 
>> I can't make that work with rasterVis::levelplot()
>> 
>> # start preparatory
>> library(raster)
>> library(rasterVis)
>> 
>> x <- raster::raster(volcano,
>>  crs = '+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0',
>>  xmn = -45, xmx = -40, ymn = 39, ymx = 47)
>> xx <- addLayer(x,x,x)
>> 
>> at <- seq(90, 200, length = 10)
>> labels <- rep(" ", length(at))
>> labels[1] <- "low"
>> labels[length(labels)] <- "high"
>> # end preparatory
>> 
>> # try as in help exchange above - ticks are labeled with numerics
>> rasterVis::levelplot(xx,
>>  colorkey = list(at = at),
>>  labels = list(labels = labels, at = at) )
>> 
>> # try as described in ?rasterVis::levelplot section for labels
>> # ticks still labeled with numerics
>> rasterVis::levelplot(xx,
>>  at = at,
>>  labels = labels )
>> 
>> I'm stumped!  How do I control the tick labels on a scalebar?
>> 
>> Thanks!
>> Ben
>> 
>> 
>>> sessionInfo()
>> R version 3.3.1 (2016-06-21)
>> Platform: x86_64-apple-darwin13.4.0 (64-bit)
>> Running under: OS X 10.11.6 (El Capitan)
>> 
>> 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] rasterVis_0.40  latticeExtra_0.6-28 RColorBrewer_1.1-2  
>> lattice_0.20-33
>> [5] raster_2.5-8sp_1.2-3
>> 
>> loaded via a namespace (and not attached):
>> [1] zoo_1.7-13rgdal_1.1-10  parallel_3.3.1hexbin_1.27.1
>> [5] Rcpp_0.12.6   grid_3.3.1viridisLite_0.1.3
>> 
>> 
>> Ben Tupper
>> Bigelow Laboratory for Ocean Sciences
>> 60 Bigelow Drive, P.O. Box 380
>> East Boothbay, Maine 04544
>> http://www.bigelow.org
>> 
>> ___
>> R-sig-Geo mailing list
>> R-sig-Geo@r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


[R-sig-Geo] rasterVis, multiple plots and scalebar labels

2016-09-23 Thread Ben Tupper
Hi,

I would like to specify the labels drawn on the scalebar for a multi-raster 
plot.  I have seen this exchange (and try to replicate for multiple rasters 
below)  

https://stat.ethz.ch/pipermail/r-help/2011-August/286705.html

I can't make that work with rasterVis::levelplot()

# start preparatory
library(raster)
library(rasterVis)

x <- raster::raster(volcano,
crs = '+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0',
xmn = -45, xmx = -40, ymn = 39, ymx = 47)  
xx <- addLayer(x,x,x)

at <- seq(90, 200, length = 10)
labels <- rep(" ", length(at))
labels[1] <- "low"
labels[length(labels)] <- "high"
# end preparatory

# try as in help exchange above - ticks are labeled with numerics
rasterVis::levelplot(xx,
 colorkey = list(at = at),
 labels = list(labels = labels, at = at) )

# try as described in ?rasterVis::levelplot section for labels
# ticks still labeled with numerics
rasterVis::levelplot(xx,
at = at,
labels = labels )

I'm stumped!  How do I control the tick labels on a scalebar?

Thanks!
Ben


> sessionInfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.6 (El Capitan)

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] rasterVis_0.40  latticeExtra_0.6-28 RColorBrewer_1.1-2  lattice_0.20-33 
   
[5] raster_2.5-8sp_1.2-3   

loaded via a namespace (and not attached):
[1] zoo_1.7-13rgdal_1.1-10  parallel_3.3.1hexbin_1.27.1
[5] Rcpp_0.12.6   grid_3.3.1viridisLite_0.1.3


Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] modis download authentication

2016-09-08 Thread Ben Tupper
Hi,

RCurl's getBinaryURL() passes the '...' and '.opts' argument to RCurl's 
getURL().  The help page for getURL() shows an example that passes the username 
and password.

Will that do the trick?

Ben


> On Sep 8, 2016, at 7:16 AM, Luca Candeloro <luca.candel...@gmail.com> wrote:
> 
> I used succesfully the function getBinaryURL from RCurl library to download
> .hdf file, as in:
> 
> content <- getBinaryURL("
> http://e4ftl01.cr.usgs.gov/MOLT/MOD11A2.005/2016.01.01/MOD11A2.A2016001.h18v04.005.2016012041335.hdf
> ")
> 
> Since http://e4ftl01.cr.usgs.gov/ has recently applied a login and pass
> authentication to retrieve data, the previous code doesn't work.
> It seems (from
> https://lpdaac.usgs.gov/sites/default/files/public/get_data/docs/Command%20Line%20Access%20Tips%20for%20Utilizing%20Earthdata%20Login.docx
> )
> that curl options should be necessarily  set.
> Does someone know how to correctly specify RCurl options in R, so that
> getBinaryURL works again?
> thanks,
> Luca
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Report Gulf of Maine jellyfish sightings to jellyf...@bigelow.org or tweet them 
to #MaineJellies -- include date, time, and location, as well as any 
descriptive information such as size or type.  Learn more at 
https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Incorrect month order in zApply function

2016-07-29 Thread Ben Tupper
rent software and comparing the 
>> results, I came to realize that the order of months for the results by 
>> raster should, in fact, be Jan-Feb-Mar-Apr-May-Jun-Jul-Aug-Sep-Oct-Nov-Dec
>> 
>> How can I control the way raster delivers the object names after using 
>> zApply, in order to sort the months in the "natural" order?
>> 
>> Greetings, -- Thiago V. dos Santos
>> 
>> PhD student
>> Land and Atmospheric Science
>> University of Minnesota
>> 
>> ___
>> R-sig-Geo mailing list
>> R-sig-Geo@r-project.org
>> https://urldefense.proofpoint.com/v2/url?u=https-3A__stat.ethz.ch_mailman_listinfo_r-2Dsig-2Dgeo=CwICAg=y2w-uYmhgFWijp_IQN0DhA=VXzrzLaooo912e5bVVEO_z5cHQXu_22lipAXBkfCXjM=tzdb3kN3Nxjo7NbPkPVqtF269bJen1bf3AzSHEwd7CA=zuokuoKIDT6cOaBD2J6ePy1klmf1J3-f3BynP_G5I-g=
> 
> 
> -- 
> Katherine (Kay) Kilpatrick
> University of Miami/RSMAS
> Ocean Science Department
> Satellite Remote Sensing Laboratory
> MSC 231
> 4600 Rickenbacker Cswy
> Miami, Fl
> ph: 305-962-3069
> kkilpatr...@rsmas.miami.edu
> 
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Report Gulf of Maine jellyfish sightings to jellyf...@bigelow.org or tweet them 
to #MaineJellies -- include date, time, and location, as well as any 
descriptive information such as size or type.  Learn more at 
https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Incorrect month order in zApply function

2016-07-29 Thread Ben Tupper
Hi,

Might you simply reorder the stack after zApply()?

> x2 <- x[[month.name]]
> names(x2)
 [1] "January"   "February"  "March" "April" "May"   "June" 
 [7] "July"  "August""September" "October"   "November"  "December" 

Cheers,
Ben



> On Jul 29, 2016, at 10:52 AM, Dominik Schneider <dosc3...@colorado.edu> wrote:
> 
> Sorry I'm not sure how to fix this, but it looks like the months are  in
> alphanumeric order, indicating they are being treated as a factor. Might be
> worth a bug report?
> 
> 
> 
> On Thursday, July 28, 2016, Thiago V. dos Santos via R-sig-Geo <
> r-sig-geo@r-project.org> wrote:
> 
>> Dear all,
>> 
>> I am using the raster package to calculate monthly averages of climatic
>> variables.
>> 
>> Essentially, this is the function I use:
>> 
>> library(raster)
>> 
>> # Create date sequence
>> idx <- seq(as.Date("1996/1/1"), as.Date("2010/12/31"), by = "day")
>> 
>> # Create raster stack and assign dates
>> r <- raster(ncol=5, nrow=5)
>> s <- stack(lapply(1:length(idx), function(x) setValues(r,
>> runif(ncell(r)
>> s <- setZ(s, idx)
>> 
>> # Calculate monthly average
>> x <- zApply(s, by=months, mean, name=month.abb[])
>> 
>> names(x)
>> [1] "April" "August" "December" "February" "January" "July" "June"
>> [8] "March" "May" "November" "October" "September"
>> getZ(x)
>> [1] "April" "August" "December" "February" "January" "July" "June"
>> [8] "March" "May" "November" "October" "September"
>> 
>> 
>> The problem here is the output of both names(x) and getZ(x). It looks like
>> a random month order is returned (even though I provide the labels), which
>> makes me confused about the results.
>> 
>> 
>> By performing the same calculation in a different software and comparing
>> the results, I came to realize that the order of months for the results by
>> raster should, in fact, be Jan-Feb-Mar-Apr-May-Jun-Jul-Aug-Sep-Oct-Nov-Dec
>> 
>> How can I control the way raster delivers the object names after using
>> zApply, in order to sort the months in the "natural" order?
>> 
>> Greetings, -- Thiago V. dos Santos
>> 
>> PhD student
>> Land and Atmospheric Science
>> University of Minnesota
>> 
>> ___
>> R-sig-Geo mailing list
>> R-sig-Geo@r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>> 
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Report Gulf of Maine jellyfish sightings to jellyf...@bigelow.org or tweet them 
to #MaineJellies -- include date, time, and location, as well as any 
descriptive information such as size or type.  Learn more at 
https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Add +1 to current value of a cell in a raster in R

2016-07-11 Thread Ben Tupper
Hi Giacomo,

I am interested to know which you find fastest - perhaps you could let us know 
some timing results?

Thanks,
Ben

> On Jul 11, 2016, at 12:21 PM, Giacomo May <giacomo_ma...@gmx.de> wrote:
> 
> Thanks for all the replies. In case anyone is interested, I asked the same 
> question on stackexchange and got the following answer:
> 
> library(dplyr)
> cel <- data_frame(cell = vec)
> tab <- cel %>% group_by(cell) %>% summarize(val = n())
> ## update your raster
> r[tab$cell] <- tab$val
> 
> I will try the soultions you guys suggested as well, thanks a lot again !
> Best,
> Giacomo
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Report Gulf of Maine jellyfish sightings to jellyf...@bigelow.org or tweet them 
to #MaineJellies -- include date, time, and location, as well as any 
descriptive information such as size or type.  Learn more at 
https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/


[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Add +1 to current value of a cell in a raster in R

2016-07-10 Thread Ben Tupper
Hi,

Interesting.  How would you use the matrix approach to increment a particular 
cell more than once with a single subassignment?  If I repeat the upper left 
raster coord in the matrix 3 times it still yields a value of 1 up there.

library(raster)
r <- raster(nrows=5,ncols=5)
r[] <- 0
idx <- matrix(c(1,1,1,1,1,1,1,5,5,1,5,5),ncol=2,byrow=TRUE) 
r[idx] <- r[idx] + 1
plot(r)
range(getValues(r))
#[1] 0 1

I could be misreading the original posting, but I think the desire is that the 
result will be increment for each repeated index using just one subassignment.  

Cheers,
Ben


> On Jul 10, 2016, at 6:45 PM, Vijay Lulla <vijaylu...@gmail.com> wrote:
> 
> Maybe something like this?
> 
> R> r <- raster(nrows=5,ncols=5)
> R> r[] <- 0
> R> idx <- matrix(c(1,1,1,5,5,1,5,5),ncol=2,byrow=TRUE) # four corners of the 
> raster!
> R> r[idx] <- r[idx] + 1
> R> image(r)
> 
> From R's ?`[` : When indexing arrays by '[' a single argument 'i' can be a 
> matrix with as many columns as there are dimensions of 'x'; the result is 
> then a vector with elements corresponding to the sets of indices in each row 
> of 'i'.
> 
> 
> On Sun, Jul 10, 2016 at 5:59 PM, Ben Tupper <btup...@bigelow.org 
> <mailto:btup...@bigelow.org>> wrote:
> Hi,
> 
> I stub my toe on this all the time (and wish I didn't).  The behavior isn't 
> limited to raster - the replacement operator `[` in general doesn't update 
> the left had side like my wild imagination might allow.  It's just a function 
> and so it must make a copy of the input.
> 
> This note seen here ?`[` sort of points out the issue... "Subassignment is 
> done sequentially, so if an index is specified more than once the latest 
> assigned value for an index will result."  Between that, the phase of the 
> moon and the pass-by-value stuff my brain starts to jumble.
> 
> On the other hand, if you have dependable indices and are simply incrementing 
> you can leverage table() for your purpose.
> 
> x <- rep(0,5)
> i <- c(1,1,1,4)
> ti <- table(i)
> tindex <- as.numeric(names(ti))
> x[tindex] <- x[tindex] + ti
> 
> Likewise for raster
> 
> library(raster)
> r <- raster(ncol=5,nrow=5)
> r[] <- 0
> vec <- c(1,1,1,3,4,5,6,7,8,8,8,9)
> tvec <- table(vec)
> tindex <- as.integer(names(tvec))
> r[tindex] <- r[tindex] + tvec
> 
> I hope there are smarter/faster ways, but in the meantime it might speed 
> things along for you.
> 
> 
> Ben
> 
> 
> > On Jul 10, 2016, at 3:34 PM, Giacomo May <giacomo_ma...@gmx.de 
> > <mailto:giacomo_ma...@gmx.de>> wrote:
> >
> > Dear R-users,
> > I am trying to add +1 to the cell value of certain cells in a raster. I 
> > have the cell numbers of the cells on which I'd like to perform said 
> > computation saved in a vector. I have a working code but with a large 
> > vector and raster it takes ages:
> >
> > r <- raster(ncol=5,nrow=5)
> > r[] <- 0
> > vec <- c(1,1,1,3,4,5,6,7,8,8,8,9)
> > for(i in 1:length(vec))
> > {
> > r[vec[i]] <- r[vec[i]] + 1
> > }
> >
> > I have already tried to use r[vec] <- r[vec] + 1 but that doesn't work 
> > properly, it just sets the values of the cells stored in the vector to 1. 
> > Does anybody know a faster way to do this ? Thanks in advance!
> >
> > ___
> > R-sig-Geo mailing list
> > R-sig-Geo@r-project.org <mailto:R-sig-Geo@r-project.org>
> > https://stat.ethz.ch/mailman/listinfo/r-sig-geo 
> > <https://stat.ethz.ch/mailman/listinfo/r-sig-geo>
> 
> Ben Tupper
> Bigelow Laboratory for Ocean Sciences
> 60 Bigelow Drive, P.O. Box 380
> East Boothbay, Maine 04544
> http://www.bigelow.org <http://www.bigelow.org/>
> 
> Report Gulf of Maine jellyfish sightings to jellyf...@bigelow.org 
> <mailto:jellyf...@bigelow.org> or tweet them to #MaineJellies -- include 
> date, time, and location, as well as any descriptive information such as size 
> or type.  Learn more at 
> https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/
>  
> <https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/>
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org <mailto:R-sig-Geo@r-project.org>
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo 
> <https://stat.ethz.ch/mailman/listinfo/r-sig-geo>
> 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Report Gulf of Maine jellyfish sightings to jellyf...@bigelow.org or tweet them 
to #MaineJellies -- include date, time, and location, as well as any 
descriptive information such as size or type.  Learn more at 
https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/


[[alternative HTML version deleted]]

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Add +1 to current value of a cell in a raster in R

2016-07-10 Thread Ben Tupper
Hi,

I stub my toe on this all the time (and wish I didn't).  The behavior isn't 
limited to raster - the replacement operator `[` in general doesn't update the 
left had side like my wild imagination might allow.  It's just a function and 
so it must make a copy of the input.

This note seen here ?`[` sort of points out the issue... "Subassignment is done 
sequentially, so if an index is specified more than once the latest assigned 
value for an index will result."  Between that, the phase of the moon and the 
pass-by-value stuff my brain starts to jumble. 

On the other hand, if you have dependable indices and are simply incrementing 
you can leverage table() for your purpose.

x <- rep(0,5)
i <- c(1,1,1,4)
ti <- table(i)
tindex <- as.numeric(names(ti))
x[tindex] <- x[tindex] + ti

Likewise for raster

library(raster)
r <- raster(ncol=5,nrow=5)
r[] <- 0
vec <- c(1,1,1,3,4,5,6,7,8,8,8,9)
tvec <- table(vec)
tindex <- as.integer(names(tvec))
r[tindex] <- r[tindex] + tvec

I hope there are smarter/faster ways, but in the meantime it might speed things 
along for you.  


Ben


> On Jul 10, 2016, at 3:34 PM, Giacomo May <giacomo_ma...@gmx.de> wrote:
> 
> Dear R-users,
> I am trying to add +1 to the cell value of certain cells in a raster. I have 
> the cell numbers of the cells on which I'd like to perform said computation 
> saved in a vector. I have a working code but with a large vector and raster 
> it takes ages:
> 
> r <- raster(ncol=5,nrow=5)
> r[] <- 0
> vec <- c(1,1,1,3,4,5,6,7,8,8,8,9)
> for(i in 1:length(vec))
> {
> r[vec[i]] <- r[vec[i]] + 1
> }
> 
> I have already tried to use r[vec] <- r[vec] + 1 but that doesn't work 
> properly, it just sets the values of the cells stored in the vector to 1. 
> Does anybody know a faster way to do this ? Thanks in advance!
> 
> ___________
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

Report Gulf of Maine jellyfish sightings to jellyf...@bigelow.org or tweet them 
to #MaineJellies -- include date, time, and location, as well as any 
descriptive information such as size or type.  Learn more at 
https://www.bigelow.org/research/srs/nick-record/nick-record-laboratory/mainejellies/

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Faster way to extract raster values using multiple polygons?

2016-04-06 Thread Ben Tupper
Hi,

The resolution of your raster data (1 degree) is much more coarse than what 
your polygons represent.  Could you short-circuit the process by assuming that 
the temp at the centroid of each polygon would suitably represent the mean 
temperature across each polygon?  Unless you have some much bigger polygons, I 
can't imagine it will be very far off. If so, then you could pretty quickly 
extract the values for each layer in the raster at each centroid.  Perhaps like 
this?

cents <- coordinates(br_sub)
v <- extract(b, cents)

Is that close enough?

Cheers,
Ben

> On Apr 6, 2016, at 8:00 AM, Thiago V. dos Santos via R-sig-Geo 
> <r-sig-geo@r-project.org> wrote:
> 
> Dear all,
> 
> I am trying to extract a time series from a raster brick using multiple 
> polygons.
> 
> The raster brick is a global temperature netcdf file with 1200 layers 
> (months) and the polygons are each of the 5567 municipalities in Brazil. I 
> intend to extract the temperature time series for each municipality.
> 
> As a final result, I would like to have a data frame containing: -the name 
> and coordinates of the municipality, -the date tag from the raster, and -the 
> extracted temperature value.
> 
> My initial, VERY SLOW attempt was something like this:
> 
> 
> library(raster)
> 
> # Create some sample raster data
> idx <- seq(as.Date("1960/1/1"), as.Date("1990/12/01"), by = "month")
> r <- raster(ncol=360, nrow=180)
> b <- brick(lapply(1:length(idx), function(x) setValues(r, runif(ncell(r)
> b <- setZ(b, idx)
> 
> # Import polygon data
> br <- getData("GADM", country="Brazil", level=2) # about 7MB to download
> 
> # Subset the SMALLEST state - only 75 municipalities
> br_sub <- br[br$NAME_1=="Sergipe" & !is.na(br$NAME_1),]
> plot(br_sub)
> 
> # Now let's extract the data for each municipality
> beginCluster()
> e <- extract(b, br_sub, fun=mean, df=T)
> endCluster()
> 
> 
> Even using the smallest state possible, this example takes about 20 minutes 
> to run on a dual-core 2.5GHz Macbook Pro using four threads. As a reference, 
> there are states with over 850 municipalities. And remember, in total there 
> are over 5500 municipalities I need to extract the data for.
> 
> I have the feeling that my code is not very optimized.
> 
> Has anybody ever dealt with this amount of data in this kind of raster 
> operation? Is there any fastest way to achieve my expected result?
> Thanks in advance,
> -- Thiago V. dos Santos
> 
> PhD student
> Land and Atmospheric Science
> 
> University of Minnesota
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Calculate percent cover in a raster

2016-02-16 Thread Ben Tupper
Hi,

I think you can use raster::reclassify() or raster::cut() to bin your rainfall.

intervals <- seq(from = 0, to = 600, by = 100)
ix <- cut(r, breaks = intervals)
tx <- table(as.vector(ix))
tx

  1   2   3   4   5   6 
 46  64  85  76 100  69 

tx/sum(tx)*100

   123456 
10.45455 14.54545 19.31818 17.27273 22.72727 15.68182 

Is that what you are looking for?


Cheers,
Ben

> On Feb 16, 2016, at 8:51 PM, Thiago V. dos Santos <thi_vel...@yahoo.com.br> 
> wrote:
> 
> Hi all,
> 
> I have a raster at 0.5 degree resolution with monthly totals of rainfall, 
> which range from 50 mm to 600 mm:
> 
> require(raster)
> 
> ## scratch a raster and fill some random values
> r <- raster(nrows=22, ncols=20, xmn=-58, xmx=-48, ymn=-33, ymx=-22)
> r[] <- round(runif(22 * 20, min=50, max=600), digits=0)
> 
> 
> How can I calculate the percentage area of the raster covered with some 
> rainfall ranges? 
> 
> Let's say for example 0 to 100, 101 to 200, 201 to 300, 301 to 400, 401 to 
> 500 and finally 501 to 600 mm? 
> Thanks in advance,
> -- Thiago V. dos Santos
> 
> PhD student
> Land and Atmospheric Science
> University of Minnesota
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] SST and chlorophyll data extraction in R

2015-09-18 Thread Ben Tupper
Hi,

On Sep 18, 2015, at 9:39 AM, Antonio Silva <aolinto@gmail.com> wrote:

> Dear R-Sig-Geo fellows
> 
> 
> This is my first post to this list. My name is Antonio Olinto and I work as
> researcher at Fisheries Institute, São Paulo, Brazil.
> 
> 
> Well, I'd like to hear suggestions on how to proceed in R to extract sea
> surface temperature and chlorophyll concentration data and calculate some
> statistics from MODIS/AQUA data in a given area.
> 
> 
> I used to do this in QGIS but available statistical parameters are limited
> and I had to work with one image at a time. I found a reference to a
> package named satin (
> https://www.r-project.org/conferences/useR-2009/slides/Villalobos+GonzalezRodriguez.pdf)
> but it seems it's not available anymore.
> 
> 
> I have several  *.L3m_MO_SST_4.bz2 and *.L3m_MO_CHL_chlor_a_4km.bz2 files
> obtained from
> http://podaac.jpl.nasa.gov/dataset/MODIS_AQUA_L3_SST_THERMAL_MONTHLY_4KM_DAYTIME
> and from http://oceandata.sci.gsfc.nasa.gov/MODISA/Mapped/Monthly/4km/chlor/
> 
> 
> I also have a shapefile with the boundaries of the area of interest. I'd
> like to have some statistics (maximum, minimum, mean, quantiles, ect.) of
> both variables in this area.
> 
> 
> Any indication of tutorials, sites or packages will be welcome.  Thanks in
> advance.
> 
> 

You might give this package a try: https://github.com/btupper/spnc It's 
essentially a wrapper around ncdf4, sp and raster and we have it configured for 
a couple of different data sources including Ocean Color's new netcdf files.  
It won't handle the .bz2 files though, just the .nc.   It is very much in it's 
"beta" stage, but it works well for us.

If it works for you, you can also try https://github.com/btupper/obpgcrawler to 
simplify downloads from the Ocean Color resources using their THREDDS 
framework.  


Cheers,
Ben





> All the best,
> 
> Antônio Olinto
> 
>   [[alternative HTML version deleted]]
> 
> ___________
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] mapview 0.5.0

2015-09-14 Thread Ben Tupper
Sweet!  Thanks for sharing! 


On Sep 13, 2015, at 6:42 AM, Tim Appelhans <tim.appelh...@gmail.com> wrote:

> Dear all,
> 
> I have put some more effort into mapview.
> The current version 0.5.0 has some new features which make the whole 
> experience much more user-friendly.
> 
> In a nutshell, changes/additions are as follows:
> 
> - mapView() is now also defined for SpatialPixelsDataFrame
> - all Spatial * DataFrame methods have gained argument 'zcol' to select 
> specific columns from the attribute table
> - SpatialPointsDataFrame method has gained argument 'radius' to scale the 
> circles according to another variable
> - added viewRGB() to render true-/false-color images of RatserStacks/Bricks 
> (like raster::plotRGB)
> - added viewExtent() to view the extent/bbox of Raster*/Spatial* objects. 
> This is useful for large objects as only the four corners of the extent need 
> to be reprojected (using raster::projectExtent)
> - defined '+'-method to easily add layers to a leaflet/mapview map or combine 
> existing maps
> - defined class 'mapview' which has two slots
>  - @object - a list with all objects that are shown on the map
>  - @map - the map
> - Raster* methods have gained argument 'maxpixels' to avoid long rendering 
> times (by default set to 50 pixels which produces acceptable times on my 
> machine)
> - enhanced leaflet integration so that you can use leaflet maps and add 
> features using mapview (e.g. '+') or use mapview to create maps and add 
> functionality provided by leaflet (using e.g. %>%)
> 
> As an example, this means that you can now do things like
> 
> mapView(meuse.grid, zcol = "soil") + viewExtent(meuse) + meuse
> 
> to view all points of meuse plus their extent on top of a raster layer of 
> meuse.grid$soil
> 
> All new functionality is highlighted in detail in the demo at
> 
> http://environmentalinformatics-marburg.github.io/web-presentations/20150723_mapView.html
> (the .Rmd source of which is now also included as a vignette in the package)
> 
> The package repository can be found at 
> https://github.com/environmentalinformatics-marburg/mapview
> 
> To install the package use
> 
> library(devtools)
> install_github("environmentalinformatics-marburg/mapview")
> 
> I hope this update will prove useful for some of you.
> Don't hesitate to send me feedback and/or suggestions.
> 
> Formal bug reports and feature requests should be filed at
> https://github.com/environmentalinformatics-marburg/mapview/issues
> 
> Best
> Tim
> 
> -- 
> #
> Tim Appelhans
> Department of Geography
> Environmental Informatics
> Philipps Universität Marburg
> Deutschhausstraße 12
> 35032 Marburg (Paketpost: 35037 Marburg)
> Germany
> 
> Tel +49 (0) 6421 28-25957
> 
> http://environmentalinformatics-marburg.de/
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] sp and latticeExtra: add colorbar for layer drawn 'under'

2015-09-02 Thread Ben Tupper
Hi,

On Aug 30, 2015, at 6:37 AM, Edzer Pebesma <edzer.pebe...@uni-muenster.de> 
wrote:

> On 08/29/2015 10:55 AM, Tim Appelhans wrote:
>> 
>> I am not sure why SpatialPolygons* objects get rendered via levelplot.
> 
> because levelplot has the understanding of plotting something in 2D,
> using colours according to the continuous variation of a third variable.

Thanks to you and Tim for the clarifications.  

I can see in the source code, spplot.R, that SpatialPolygonsDataFrame and 
SpatialLinesDataFrame are handled by levelplot; thanks for pointing that out. 
That SpatialPointsDataFrame is handled by xyplot gives me pause now.  In fact, 
if I think about it it confuses me, so I best not think about that first thing 
in the morning!

I agree with Tim that starting with the raster first and then adding the 
polygons with latticeExtra::as.layer() is more intuitive. 

Thanks again,
Ben

> -- 
> Edzer Pebesma
> Institute for Geoinformatics (ifgi),  University of Münster,
> Heisenbergstraße 2, 48149 Münster, Germany; +49 251 83 33081
> Journal of Statistical Software:   http://www.jstatsoft.org/
> Computers & Geosciences:   http://elsevier.com/locate/cageo/
> Spatial Statistics Society http://www.spatialstatistics.info
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


[R-sig-Geo] sp and latticeExtra: add colorbar for layer drawn 'under'

2015-08-28 Thread Ben Tupper
Hello,

I have drawn on the following posting to draw a raster 'under' a set of 
polygons as shown in the image link below.  The data used is available at the 
third link (about 650KB).

Posting: 
http://stackoverflow.com/questions/27062768/how-to-plot-additional-raster-with-spplot

Image: https://dl.dropboxusercontent.com/u/8433654/sp-over-plot.png

Example data: https://dl.dropboxusercontent.com/u/8433654/example.RData

Here is a brief description of each variable plotted.

R is a single layer RasterStack of sea surface temperatures
qa is a SpatialPolygonsDataFrame of fisheries management polygons
spdfbb is also a SpatialPolygonsDataFrame that contains a single polygon 
(created from the extent of qa)

sp::spplot(spdfbb, 
   colorkey = FALSE,
   sp.layout = list(b = list('sp.polygons', qa, col = 'grey', first = FALSE))) 
+ 
   latticeExtra::as.layer(spplot(R), under = TRUE)

Is it possible add a colorbar for the raster, R, as it might appear if I 
called...

spplot(R)

Session info is below my signature.

Thanks!
Ben

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

 sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.9.5 (Mavericks)

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] latticeExtra_0.6-26 lattice_0.20-33 rgeos_0.3-8 
obpgcrawler_0.1 ecocastmap_0.1 
 [6] RColorBrewer_1.1-2  ggplot2_1.0.1   rgdal_0.9-3 spnc_0.1   
 raster_2.4-15  
[11] sp_1.1-1   

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.0  magrittr_1.5 MASS_7.3-43  munsell_0.4.2
colorspace_1.2-6 R6_2.1.1
 [7] stringr_1.0.0httr_1.0.0   plyr_1.8.3   tools_3.2.2  
grid_3.2.2   gtable_0.1.2
[13] digest_0.6.8 reshape2_1.4.1   ncdf4_1.13   curl_0.9.3   
stringi_0.5-5scales_0.2.5
[19] XML_3.98-1.3 proto_0.3-10 
___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] sp and latticeExtra: add colorbar for layer drawn 'under'

2015-08-28 Thread Ben Tupper
Hi,

Perfect!  I wouldn't have gotten there in a hundred years.  

Thanks,
Ben

On Aug 28, 2015, at 10:51 AM, Tim Appelhans tim.appelh...@gmail.com wrote:

 Ben,
 you could specify the colorkey manually in the spplot call for spdfbb:
 
 sp::spplot(spdfbb,
   colorkey = list(col = bpy.colors(101), width = 1,
   at = seq(0, 30, length.out = 100),
   space = top),
   sp.layout = list(b = list('sp.polygons', qa, col = 'grey', first = 
 FALSE))) +
  latticeExtra::as.layer(spplot(R, at = seq(0, 30, length.out = 100)), under = 
 TRUE)
 
 
 You simply need to make sure to pass the same specs to the spplot call to R.
 
 HTH
 Tim
 
 On 28.08.2015 16:33, Ben Tupper wrote:
 Hello,
 
 I have drawn on the following posting to draw a raster 'under' a set of 
 polygons as shown in the image link below.  The data used is available at 
 the third link (about 650KB).
 
 Posting: 
 http://stackoverflow.com/questions/27062768/how-to-plot-additional-raster-with-spplot
 
 Image: https://dl.dropboxusercontent.com/u/8433654/sp-over-plot.png
 
 Example data: https://dl.dropboxusercontent.com/u/8433654/example.RData
 
 Here is a brief description of each variable plotted.
 
 R is a single layer RasterStack of sea surface temperatures
 qa is a SpatialPolygonsDataFrame of fisheries management polygons
 spdfbb is also a SpatialPolygonsDataFrame that contains a single polygon 
 (created from the extent of qa)
 
 sp::spplot(spdfbb,
colorkey = FALSE,
sp.layout = list(b = list('sp.polygons', qa, col = 'grey', first = 
 FALSE))) +
latticeExtra::as.layer(spplot(R), under = TRUE)
 
 Is it possible add a colorbar for the raster, R, as it might appear if I 
 called...
 
 spplot(R)
 
 Session info is below my signature.
 
 Thanks!
 Ben
 
 Ben Tupper
 Bigelow Laboratory for Ocean Sciences
 60 Bigelow Drive, P.O. Box 380
 East Boothbay, Maine 04544
 http://www.bigelow.org
 
 sessionInfo()
 R version 3.2.2 (2015-08-14)
 Platform: x86_64-apple-darwin13.4.0 (64-bit)
 Running under: OS X 10.9.5 (Mavericks)
 
 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] latticeExtra_0.6-26 lattice_0.20-33 rgeos_0.3-8 
 obpgcrawler_0.1 ecocastmap_0.1
  [6] RColorBrewer_1.1-2  ggplot2_1.0.1   rgdal_0.9-3 spnc_0.1
 raster_2.4-15
 [11] sp_1.1-1
 
 loaded via a namespace (and not attached):
  [1] Rcpp_0.12.0  magrittr_1.5 MASS_7.3-43  munsell_0.4.2
 colorspace_1.2-6 R6_2.1.1
  [7] stringr_1.0.0httr_1.0.0   plyr_1.8.3   tools_3.2.2  
 grid_3.2.2   gtable_0.1.2
 [13] digest_0.6.8 reshape2_1.4.1   ncdf4_1.13   curl_0.9.3   
 stringi_0.5-5scales_0.2.5
 [19] XML_3.98-1.3 proto_0.3-10
 ___
 R-sig-Geo mailing list
 R-sig-Geo@r-project.org
 https://stat.ethz.ch/mailman/listinfo/r-sig-geo
 
 -- 
 #
 Tim Appelhans
 Department of Geography
 Environmental Informatics
 Philipps Universität Marburg
 Deutschhausstraße 12
 35032 Marburg (Paketpost: 35037 Marburg)
 Germany
 
 Tel +49 (0) 6421 28-25957
 
 http://environmentalinformatics-marburg.de/
 
 ___
 R-sig-Geo mailing list
 R-sig-Geo@r-project.org
 https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] sp and latticeExtra: add colorbar for layer drawn 'under'

2015-08-28 Thread Ben Tupper
That works like a charm.

It's sort of non-intuitive that I would use the colorkey argument for the plot 
of the polygons since color key is documented for levelplot.  In my naive view 
I would looked to xyplot when plotting polygons. I'm still in the grope and 
thrash stage with lattice/spplot (and occasionally enjoying it.)

Thanks so much!

Ben

On Aug 28, 2015, at 10:51 AM, Tim Appelhans tim.appelh...@gmail.com wrote:

 Ben,
 you could specify the colorkey manually in the spplot call for spdfbb:
 
 sp::spplot(spdfbb,
   colorkey = list(col = bpy.colors(101), width = 1,
   at = seq(0, 30, length.out = 100),
   space = top),
   sp.layout = list(b = list('sp.polygons', qa, col = 'grey', first = 
 FALSE))) +
  latticeExtra::as.layer(spplot(R, at = seq(0, 30, length.out = 100)), under = 
 TRUE)
 
 
 You simply need to make sure to pass the same specs to the spplot call to R.
 
 HTH
 Tim
 
 On 28.08.2015 16:33, Ben Tupper wrote:
 Hello,
 
 I have drawn on the following posting to draw a raster 'under' a set of 
 polygons as shown in the image link below.  The data used is available at 
 the third link (about 650KB).
 
 Posting: 
 http://stackoverflow.com/questions/27062768/how-to-plot-additional-raster-with-spplot
 
 Image: https://dl.dropboxusercontent.com/u/8433654/sp-over-plot.png
 
 Example data: https://dl.dropboxusercontent.com/u/8433654/example.RData
 
 Here is a brief description of each variable plotted.
 
 R is a single layer RasterStack of sea surface temperatures
 qa is a SpatialPolygonsDataFrame of fisheries management polygons
 spdfbb is also a SpatialPolygonsDataFrame that contains a single polygon 
 (created from the extent of qa)
 
 sp::spplot(spdfbb,
colorkey = FALSE,
sp.layout = list(b = list('sp.polygons', qa, col = 'grey', first = 
 FALSE))) +
latticeExtra::as.layer(spplot(R), under = TRUE)
 
 Is it possible add a colorbar for the raster, R, as it might appear if I 
 called...
 
 spplot(R)
 
 Session info is below my signature.
 
 Thanks!
 Ben
 
 Ben Tupper
 Bigelow Laboratory for Ocean Sciences
 60 Bigelow Drive, P.O. Box 380
 East Boothbay, Maine 04544
 http://www.bigelow.org
 
 sessionInfo()
 R version 3.2.2 (2015-08-14)
 Platform: x86_64-apple-darwin13.4.0 (64-bit)
 Running under: OS X 10.9.5 (Mavericks)
 
 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] latticeExtra_0.6-26 lattice_0.20-33 rgeos_0.3-8 
 obpgcrawler_0.1 ecocastmap_0.1
  [6] RColorBrewer_1.1-2  ggplot2_1.0.1   rgdal_0.9-3 spnc_0.1
 raster_2.4-15
 [11] sp_1.1-1
 
 loaded via a namespace (and not attached):
  [1] Rcpp_0.12.0  magrittr_1.5 MASS_7.3-43  munsell_0.4.2
 colorspace_1.2-6 R6_2.1.1
  [7] stringr_1.0.0httr_1.0.0   plyr_1.8.3   tools_3.2.2  
 grid_3.2.2   gtable_0.1.2
 [13] digest_0.6.8 reshape2_1.4.1   ncdf4_1.13   curl_0.9.3   
 stringi_0.5-5scales_0.2.5
 [19] XML_3.98-1.3 proto_0.3-10
 ___
 R-sig-Geo mailing list
 R-sig-Geo@r-project.org
 https://stat.ethz.ch/mailman/listinfo/r-sig-geo
 
 -- 
 #
 Tim Appelhans
 Department of Geography
 Environmental Informatics
 Philipps Universität Marburg
 Deutschhausstraße 12
 35032 Marburg (Paketpost: 35037 Marburg)
 Germany
 
 Tel +49 (0) 6421 28-25957
 
 http://environmentalinformatics-marburg.de/
 
 ___
 R-sig-Geo mailing list
 R-sig-Geo@r-project.org
 https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] OSX, rgdal, GDAL drivers and HDF4

2015-06-03 Thread Ben Tupper
Hi,

On Jun 2, 2015, at 1:56 PM, Shaun Walbridge swalbri...@esri.com wrote:

 Have you tried with the homebrew project? HDF4 isn¹t a default supported
 driver, but it¹s easy enough to add:
 
  brew install hdf4
  # prefer hdf4 links over NetCDF
  brew link --overwrite hdf4
  brew install gdal --complete --enable-unsupported --with-hdf4
 
  # check what drivers are installed, list should include Œhdf4¹:
  gdal-config --formats
 
 I¹d use that as a starting point.
 

Thanks!  I have not used brew before but it seems like it should be easy, or 
will be as soon as I figure out what this means...

ben@gale ~ $ brew install hdf4
Error: No available formula for hdf4 
Searching formulae...
Searching taps...
homebrew/versions/hdf4


Cheers,
Ben



 Cheers,
 Shaun
 
 
 
 On 6/2/15, 12:11 PM, Ben Tupper btup...@bigelow.org wrote:
 
 Hello,
 
 This is my attempt to look before I leap into installing GDAL on OSX.
 (You can probably hear my pitiful groaning and knee-knocking in the
 background.)
 
 I want to read many HDF4 files for which I do not have the GDAL HDF4
 driver installed.  I used William Kyngesburye's nice framework
 (http://www.kyngchaos.com/software:frameworks) to install GDAL but it
 came without the HDF4 driver.
 
 Reading this somewhat dated exchange...
 
 http://r-sig-geo.2731867.n2.nabble.com/Read-HDF-files-td6750856.html
 
 ... I think I understand that if I want the HDF4 driver I must build GDAL
 on my system manually.  Is my understanding correct, or is there another
 (easier) way to read HDF4 files directly in R?
 
 Thanks!
 Ben
 
 
 library(rgdal)
 Loading required package: sp
 rgdal: version: 0.9-3, (SVN revision 530)
 Geospatial Data Abstraction Library extensions to R successfully loaded
 Loaded GDAL runtime: GDAL 1.11.2, released 2015/02/10
 Path to GDAL shared files:
 /Library/Frameworks/R.framework/Versions/3.2/Resources/library/rgdal/gdal
 Loaded PROJ.4 runtime: Rel. 4.9.1, 04 March 2015, [PJ_VERSION: 491]
 Path to PROJ.4 shared files:
 /Library/Frameworks/R.framework/Versions/3.2/Resources/library/rgdal/proj
 Linking to sp version: 1.1-0
 x - gdalDrivers()
 any(x$name %in% c(HDF4, HDF))
 [1] FALSE
 
 sessionInfo()
 R version 3.2.0 (2015-04-16)
 Platform: x86_64-apple-darwin13.4.0 (64-bit)
 Running under: OS X 10.9.5 (Mavericks)
 
 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] rgdal_0.9-3 sp_1.1-0
 
 loaded via a namespace (and not attached):
 [1] grid_3.2.0  lattice_0.20-31
 
 
 
 Ben Tupper
 Bigelow Laboratory for Ocean Sciences
 60 Bigelow Drive, P.O. Box 380
 East Boothbay, Maine 04544
 http://www.bigelow.org
 
 ___
 R-sig-Geo mailing list
 R-sig-Geo@r-project.org
 https://stat.ethz.ch/mailman/listinfo/r-sig-geo
 
 

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


[R-sig-Geo] OSX, rgdal, GDAL drivers and HDF4

2015-06-02 Thread Ben Tupper
Hello,

This is my attempt to look before I leap into installing GDAL on OSX. (You can 
probably hear my pitiful groaning and knee-knocking in the background.)

I want to read many HDF4 files for which I do not have the GDAL HDF4 driver 
installed.  I used William Kyngesburye's nice framework 
(http://www.kyngchaos.com/software:frameworks) to install GDAL but it came 
without the HDF4 driver.

Reading this somewhat dated exchange... 

http://r-sig-geo.2731867.n2.nabble.com/Read-HDF-files-td6750856.html

... I think I understand that if I want the HDF4 driver I must build GDAL on my 
system manually.  Is my understanding correct, or is there another (easier) way 
to read HDF4 files directly in R?

Thanks!
Ben


 library(rgdal)
Loading required package: sp
rgdal: version: 0.9-3, (SVN revision 530)
 Geospatial Data Abstraction Library extensions to R successfully loaded
 Loaded GDAL runtime: GDAL 1.11.2, released 2015/02/10
 Path to GDAL shared files: 
/Library/Frameworks/R.framework/Versions/3.2/Resources/library/rgdal/gdal
 Loaded PROJ.4 runtime: Rel. 4.9.1, 04 March 2015, [PJ_VERSION: 491]
 Path to PROJ.4 shared files: 
/Library/Frameworks/R.framework/Versions/3.2/Resources/library/rgdal/proj
 Linking to sp version: 1.1-0 
 x - gdalDrivers()
 any(x$name %in% c(HDF4, HDF))
[1] FALSE

 sessionInfo()
R version 3.2.0 (2015-04-16)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.9.5 (Mavericks)

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] rgdal_0.9-3 sp_1.1-0   

loaded via a namespace (and not attached):
[1] grid_3.2.0  lattice_0.20-31



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] summing rasters with a condition given by other rasters

2015-05-18 Thread Ben Tupper
Hi Martin,

On May 18, 2015, at 12:22 PM, Martin Brandt martin.bra...@mailbox.org wrote:

 Hi Eder,
 
 yes, i tried to include na.rm:
 
 sum_segment - function(x, ...) {
 mean(x[(x[1]+2):(x[2] + 2)], na.rm=TRUE)
 } 
 
 but as long my stack contains any NA values, the function will not run with
 calc:
 s - calc(b, sum_segment)
 Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : 
  cannot use this function
 
 or
 
 s - calc(b, sum_segment, na.rm=T)
 Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : 
  cannot use this function. Perhaps add '...' or 'na.rm' to the function
 arguments?
 
 not sure how to make the function run and ignore all NAs..
 

This function is designed to accept further arguments for other functions 
within the its body.  So, if you pass na.rm = TRUE to sum_segment() then it 
will trickle down, so to speak, to sum().  The following should work for sum or 
mean.

sum_segment - function(x, ...) {
  sum(x[(x[1]+2):(x[2] + 2)],...)
}

mean_segment - function(x, ...) {
  mean(x[(x[1]+2):(x[2] + 2)],...)
}


s - calc(b, sum_segment, na.rm = TRUE)
m - calc(b, mean_segment, na.rm = TRUE)

s
#class   : RasterLayer 
# dimensions  : 77, 101,   (nrow, ncol, ncell)
# resolution  : 1, 1  (x, y)
# extent  : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=merc 
# data source : in memory
# names   : layer 
# values  : 0, 2295  (min, max)

m
# class   : RasterLayer 
# dimensions  : 77, 101,   (nrow, ncol, ncell)
# resolution  : 1, 1  (x, y)
# extent  : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=merc 
# data source : in memory
# names   : layer 
# values  : 0, 255  (min, max)



If that doesn't work (whether you use mean() or sum()) then something else is 
happening and you'll want to post a small runnable example of what you are 
doing.   
 
Cheers,
Ben

 
 
 
 
 --
 View this message in context: 
 http://r-sig-geo.2731867.n2.nabble.com/summing-rasters-with-a-condition-given-by-other-rasters-tp7588222p7588272.html
 Sent from the R-sig-geo mailing list archive at Nabble.com.
 
 ___
 R-sig-Geo mailing list
 R-sig-Geo@r-project.org
 https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] summing rasters with a condition given by other rasters

2015-05-10 Thread Ben Tupper
Hi Martin,

On May 10, 2015, at 4:42 PM, Martin Brandt martin.bra...@mailbox.org wrote:

 Hi Ben,
 
 thanks again, I see, but i'm not sure if i understand it correctly. The
 thing is that each pixel in the rasters sos and eos has different values,
 i.e. the start of season and end of season is not the same for each pixel.
 Thus, I cannot really define eos and sos but need to use the given rasters
 containing the values..
 

Oo.  I think I see what you are after.  I'll bet there are better ways, but 
my brute force and ignorance approach would be to prepend your start-of-season 
raster (sos) and end-of-season raster (eos) to your raster data. I would still 
use calc but modify the sum_segment function.  After the computation I would 
then drop the sos and eos layer form the data.  Note that sos and eos still 
have to be numeric indices into the layers of the data, b.

library(raster)
# create a multiple layer brick
b - brick(system.file(external/rlogo.grd, package=raster))
# add layers
b - addLayer(b,b,b)
b
# class   : RasterStack 
# dimensions  : 77, 101, , 9  (nrow, ncol, ncell, nlayers)
# resolution  : 1, 1  (x, y)
# extent  : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=merc 
# names   : red.1, green.1, blue.1, red.2, green.2, blue.2, red.3, green.3, 
blue.3 
# min values  : 0,   0,  0, 0,   0,  0, 0,   0, 
 0 
# max values  :   255, 255,255,   255, 255,255,   255, 255, 
   255 

# define the sos and eos by indexed position
# sos will range from 1 to 4
sos - raster(matrix(sample(1:4, ncell(b), replace = TRUE), nrow = nrow(b), 
ncol = ncol(b)),
   template = b)
   
#eos will range from 6 to 9
eos -  raster(matrix(sample(6:nlayers(b), ncell(b), replace = TRUE), nrow = 
nrow(b), ncol = ncol(b)),
   template = b)

# prepend sos and eos to your data
b - addLayer(sos, eos, b)

# define the summing function - add 2 to account for sos and eos at the start
sum_segment - function(x, ...) {
   sum(x[(x[1]+2):(x[2] + 2)],...)
}

# run the computation
s - calc(b, sum_segment)

#restore b
b - dropLayer(b, c(1,2))

s
#class   : RasterLayer 
#dimensions  : 77, 101,   (nrow, ncol, ncell)
#resolution  : 1, 1  (x, y)
#extent  : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=merc 
#data source : in memory
#names   : layer 
#values  : 0, 2295  (min, max)

b
#class   : RasterStack 
#dimensions  : 77, 101, , 9  (nrow, ncol, ncell, nlayers)
#resolution  : 1, 1  (x, y)
#extent  : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=merc 
#names   : red.1, green.1, blue.1, red.2, green.2, blue.2, red.3, green.3, 
blue.3 
#min values  : 0,   0,  0, 0,   0,  0, 0,   0,  
0 
#max values  :   255, 255,255,   255, 255,255,   255, 255,  
  255 

You might be able to do something similar with the overlay(). If that doesn't 
do it then we'll both have to wait for someone to come to our rescue!

Cheers,
Ben








 cheers,
 Martin
 
 
 
 
 --
 View this message in context: 
 http://r-sig-geo.2731867.n2.nabble.com/summing-rasters-with-a-condition-given-by-other-rasters-tp7588222p7588233.html
 Sent from the R-sig-geo mailing list archive at Nabble.com.
 
 ___
 R-sig-Geo mailing list
 R-sig-Geo@r-project.org
 https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] summing rasters with a condition given by other rasters

2015-05-10 Thread Ben Tupper
Hi,

On May 10, 2015, at 7:37 AM, Martin Brandt martin.bra...@mailbox.org wrote:

 Hi Ben,
 
 many thanks for the detailed answer. The code works fine, but when I use
 rasters for eos and sos instead of numbers, i get an error:
 
 
 
 b - brick(system.file(external/rlogo.grd, package=raster))
 
 b - addLayer(b,b,b)
 b
 
 sos - raster(system.file(external/rlogo.grd, package=raster))
 eos - raster(system.file(external/rlogo.grd, package=raster))
 
 
 sum_segment - function(x, from = sos, to = eos, ...) {
  sum(x[from:to],...)
 }
 
 s - calc(b, sum_segment)
 
 Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) : 
  cannot use this function
 
 am I doing something wrong?

Yes, as tempting as it is to do otherwise you really do have to use numeric 
position indices.  Inside the function sum_segment the value of x is simple a 
numeric vector. Within the scope of the function the context of the pixels 
embedded in the raster object is temporarily lost - they are just a vector of 
numbers.  

To work with the calc() function you must first compute the position indices 
for sos and eos using which().

sos - which(names(b) == blue.1)  # you would substitue the name of your 
layer for blue.1
eos - which(names(b) == green.3) # and again for green.3

Cheers,
Ben


 
 
 
 
 --
 View this message in context: 
 http://r-sig-geo.2731867.n2.nabble.com/summing-rasters-with-a-condition-given-by-other-rasters-tp7588222p7588226.html
 Sent from the R-sig-geo mailing list archive at Nabble.com.
 
 ___
 R-sig-Geo mailing list
 R-sig-Geo@r-project.org
 https://stat.ethz.ch/mailman/listinfo/r-sig-geo



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] summing rasters with a condition given by other rasters

2015-05-09 Thread Ben Tupper

On May 9, 2015, at 11:54 AM, Martin Brandt martin.bra...@mailbox.org wrote:

 I have the following issue to solve:
 There is a MODIS NDVI time series with 23 images for one year, named ndvi_01
 to ndvi_23, stored in a raster brick called MODIS.NDVI.2010. Then i have a
 raster with integer values from 1-23 representing the start of the growing
 season (SOS), and the end (EOS), e.g. SOS = 13 and EOS = 21 for one pixel.
 What i am trying to do is to create a raster (let's call it SEASON) which
 sums all NDVI values from ndvi_01 to ndvi_23 which are between SOS and EOS,
 for the example pixel that would be ndvi_13 to ndvi_21.
 
 Is this possible with the raster package?
 

On May 9, 2015, at 11:54 AM, Martin Brandt martin.bra...@mailbox.org wrote:

 I have the following issue to solve:
 There is a MODIS NDVI time series with 23 images for one year, named ndvi_01
 to ndvi_23, stored in a raster brick called MODIS.NDVI.2010. Then i have a
 raster with integer values from 1-23 representing the start of the growing
 season (SOS), and the end (EOS), e.g. SOS = 13 and EOS = 21 for one pixel.
 What i am trying to do is to create a raster (let's call it SEASON) which
 sums all NDVI values from ndvi_01 to ndvi_23 which are between SOS and EOS,
 for the example pixel that would be ndvi_13 to ndvi_21.
 
 Is this possible with the raster package?
 

Hi,

I think it is possible.  Here is one way using the calc() function in the 
raster package.

# create a multiple layer brick
b - brick(system.file(external/rlogo.grd, package=raster))
# add layers
b - addLayer(b,b,b)
b
# class   : RasterStack 
# dimensions  : 77, 101, , 9  (nrow, ncol, ncell, nlayers)
# resolution  : 1, 1  (x, y)
# extent  : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=merc 
# names   : red.1, green.1, blue.1, red.2, green.2, blue.2, red.3, green.3, 
blue.3 
# min values  : 0,   0,  0, 0,   0,  0, 0,   0, 
 0 
# max values  :   255, 255,255,   255, 255,255,   255, 255, 
   255 

# define the sos and eos by indexed position
sos - 3  # blue.1
eos - 8  # green.3

# define a function to sum along that segment of pixels
# @param x a vector of pixels at a particular location
# @param from index of the first pixel of the segment to sum
# @param to index of the last pixel in the segment to sum
# @param ... other arguments for sum()
# @return the sum of pixels long the segment from:to
sum_segment - function(x, from = sos, to = eos, ...) {
   sum(x[from:to],...)
}

# apply the function across the entire brick
s - calc(b, sum_segment)
s
# class   : RasterLayer 
# dimensions  : 77, 101,   (nrow, ncol, ncell)
# resolution  : 1, 1  (x, y)
# extent  : 0, 101, 0, 77  (xmin, xmax, ymin, ymax)
# coord. ref. : +proj=merc 
# data source : in memory
# names   : layer 
# values  : 0, 1530  (min, max)

Does that do what you want?

Cheers,
Ben

 kind regards,
 Martin 
 
 
 
 --
 View this message in context: 
 http://r-sig-geo.2731867.n2.nabble.com/summing-rasters-with-a-condition-given-by-other-rasters-tp7588222.html
 Sent from the R-sig-geo mailing list archive at Nabble.com.
 
 ___
 R-sig-Geo mailing list
 R-sig-Geo@r-project.org
 https://stat.ethz.ch/mailman/listinfo/r-sig-geo

Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org

___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


Re: [R-sig-Geo] Pole centric map with Raster?

2015-04-01 Thread Ben Tupper
Hello again,

Thanks again for your help - it really gave me the push I needed.  Below is a 
stripped down version of your script that projects the datasets::volcano matrix 
over the north pole.  In case it is of some use to others, I have added some 
notes one what I think is happening.  If you run the script you'll see that I 
am still fiddling with the graticules (reaching 90N and the one missing at 180).

Thanks also for making me aware of the remote package - that looks really 
useful.

Cheers and thanks,
Ben



### START
library(raster)
library(rgdal)
library(rgeos)
library(rworldmap)
library(RColorBrewer)

data(coastsCoarse, package = 'rworldmap')
# the crs of coastsCoarse has a leading space, this trims it
crs(coastsCoarse) - CRS(+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs 
+towgs84=0,0,0)

# the desrired projection
ster - +proj=stere +lat_0=90 +lon_0=-30 

# map view limits
xmn - -180
xmx - 180
ymn - 30
ymx - 90

# create a raster from datasets::volcano
r - raster::raster(volcano,
xmn = xmn, xmx = xmx, ymn = ymn, ymx = ymx, 
crs = +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0)

# if the raster extends into opposite hemisphere it helps to crop it
#r - crop(b, extent(xmn, xmx, ymn, ymx))

# create a polygon used for trimming the map segments
# bounding box from lower left clockwise
bb - cbind(x = c(xmn, xmn, xmx, xmx, xmn),
y = c(ymn, ymx, ymx, ymn, ymn))
# convert to Spatial   
SP - sp::SpatialPolygons(
   list(sp::Polygons(
  list(sp::Polygon(bb)), 1)),
   proj4string = sp::CRS(sp::proj4string(coastsCoarse))
   )

# compute where map bounding box and map segements overlap
# I think this amounts to cropping the map segments
gI - rgeos::gIntersects(coastsCoarse, SP, byid = TRUE)
out - vector(mode = list, length = length(which(gI)))
ii - 1
for (i in seq(along = gI)) {
   if (gI[i]) {
  out[[ii]] - rgeos::gIntersection(coastsCoarse[i, ], SP)
  row.names(out[[ii]]) - row.names(coastsCoarse)[i]
   ii - ii + 1
   }
}
nh_coasts - do.call(rbind, out)

# project the coastline map segments
nh_coasts_ster - sp::spTransform(nh_coasts, CRS(ster))

# make graticules and project
gr - sp::gridlines(nh_coasts,
   easts = seq(xmn, xmx, by = 20),
   norths = seq(ymn, ymx, by = 10),
   ndiscr = length(xmn:xmx))
pgr - sp::spTransform(gr, CRS(ster))

# project the raster volcano data
projr - projectRaster(r, crs = ster)

# sp.layout elements
lout - list(
   list(sp.lines, nh_coasts_ster, col = grey30, grid = TRUE),
   list(sp.lines, pgr, col = 'grey50', lty = 'dashed'))

# pretty colors function from RColorBrewer
clrs - colorRampPalette(brewer.pal(9, YlOrRd))

# compute steps for coloring
data_range - range(values(projr), na.rm = TRUE)
steps - 10

polar_map - sp::spplot(projr, sp.layout = lout,
   col.regions = clrs(steps),
   at = seq(data_range[1], data_range[2], length = steps),
   par.settings = list(axis.line = list(col = 1)),
   colorkey = list(height = 0.75, width = 1))

print(polar_map)

### END



On Mar 27, 2015, at 5:14 PM, Tim Appelhans tim.appelh...@gmail.com wrote:

 Ben
 here's some code I used for a paper.
 
 Is this producing what you want?
 
 
 
 library(remote)
 
 ## EXAMPLE I ##
 ###
 library(rworldmap)
 library(rgdal)
 library(rgeos)
 library(gridExtra)
 library(RColorBrewer)
 
 ## load data
 data(vdendool)
 data(coastsCoarse)
 
 ## calculate 4 leading modes
 nh_modes - eot(x = vdendool, y = NULL, n = 4, reduce.both = FALSE,
standardised = FALSE, verbose = TRUE)
 
 ## create coastal outlines
 ster - CRS(+proj=stere +lat_0=90 +lon_0=-45)
 xmin - -180
 xmax - 180
 ymin - 20
 ymax - 90 # Coordinates for bounding box
 bb - cbind(x = c(xmin, xmin, xmax, xmax, xmin),
y = c(ymin, ymax, ymax, ymin, ymin))#Create bounding box
 SP - SpatialPolygons(list(Polygons(list(Polygon(bb)), 1)),
  proj4string = CRS(proj4string(coastsCoarse)))
 
 gI - gIntersects(coastsCoarse, SP, byid = TRUE)
 out - vector(mode = list, length = length(which(gI)))
 ii - 1
 
 for (i in seq(along = gI)) if (gI[i]) {
  out[[ii]] - gIntersection(coastsCoarse[i, ], SP)
  row.names(out[[ii]]) - row.names(coastsCoarse)[i]
  ii - ii + 1
 }
 
 nh_coasts - do.call(rbind, out)
 nh_coasts_ster - spTransform(nh_coasts, ster)
 
 lout - list(sp.lines, nh_coasts_ster,
 col = grey30, grid = TRUE)
 
 ## define colours
 clrs - colorRampPalette(rev(brewer.pal(9, RdBu)))
 
 ## project modes to polar stereographic CRS
 mode1 - projectRaster(nh_modes[[1]]@r_predictor, crs = ster)
 
 spplot(mode1, sp.layout = lout,
   col.regions = clrs(1000), at = seq(-1, 1, 0.2),
   par.settings = list(axis.line = list(col = 0)),
   colorkey = list(height = 0.75, width = 1))
 
 
 Tim
 
 
 
 On 27.03.2015 21:20, Ben Tupper wrote:
 Hello,
 
 I'm learning how to use Raster* objects and ultimately hope to draw rasters 
 from

  1   2   >