[R-sig-Geo] help using SVC_mle of library varycoef

2023-07-23 Thread Emanuele Barca
Hi, this is emanuele barca and I would like to learn the library 
varycoef.
I created a simulation of an ideal spatial dataset (gaussian) and 
applied SVC_mle function:


set.seed(1234)

library(gstat)

# create structure
nx <- 100
ny <- 100
xy <- expand.grid(1:nx, 1:ny)
names(xy) <- c("x","y")

g.dummy <- gstat(formula = z ~ 1 + x + I(y^0.5), locations = ~ x + y, 
dummy = T, beta = c(1, 0.01, 0.005),
 model = vgm(psill = 0.025, range = 20, model = 'Ste', 
kappa = 10), nmax = 20)


yy <- predict(g.dummy, newdata = xy, nsim = 1)


xy.reduced <- as.data.frame(matrix(ncol = 3, nrow = 0))
for (i in 1:5000){
  xy.reduced[i, ] <- yy[i*2, 1:3]
}

Fact<- 20/100 #% of reduction about 80%
training <- sample(nrow(xy.reduced), trunc(Fact*nrow(xy.reduced)))
Xtraining <- xy.reduced[training, ]
Xtest <- xy.reduced[-training, ]
df_train <- Xtraining
colnames(df_train) <- c("X", "Y", "sim")

fit_svc <- SVC_mle(sim ~ X + Y, data = df_train, locs = df_train[, 
1:2])#

coef(fit_svc)
summary(fit_svc)

but it returns an error of the covariance matrix.
 Could someone help me to overcome the error?

thanks in advance

emanuele

___
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 with spTimer or spTDyn to estimate the Bayesian Gaussian Process Model

2021-02-03 Thread alex_rugu--- via R-sig-Geo
I am getting the following error when running the below script for the Bayesian 
Gaussian Process (GP) Model
using spTimer or spTDyn
#Error
 Output: GP models 
Error in spGP.Gibbs(formula = formula, data = data, time.data = time.data,  : 
   Error: Years, Months, and Days are misspecified,
 i.e., total number of observations in the data set should be equal to N
  : N = n * r * T 
   where, N = total number of observations in the data,
          n = total number of sites,
          r = total number of years,
          T = total number of days. 

###Script
library(spTimer)
library(spTDyn)
library(tidyverse)
library(ggmap)


register_google(key="your key")
getOption("ggmap")


#Data to be analyzed is from plm package
#It is a US States Production, which is a panel of 48 observations from 1970 to 
1986
#A data frame containing :
#state: the state
#year : the year
#region : the region
#pcap : public capital stock
#hwy :  highway and streets
#water : water and sewer facilities
#util : other public buildings and structures
#pc : private capital stock
#gsp : gross state product
#emp :labor input measured by the employment in non–agricultural payrolls
#unemp : state unemployment rates 

#Get data
data("Produc", package = "plm")
glimpse(Produc)


#Estimate Geolocation of states to account for spill over effects
states_df <- data.frame(as.character(unique(Produc$state)))
names(states_df)<- c("state")


state_geo_df <- mutate_geocode(states_df, state)  #from ggmap

#Join the data
Product_geo <- full_join(state_geo_df, Produc)
glimpse(Product_geo)


#Create the time series variable
#number of state
ns <- length(unique(Product_geo$state))


#number of year
ny <- length(unique(Product_geo$year))


# I want to do Spatio-Temporal Bayesian Modeling Using spTimer or spTDyn 
#defines the time series in the Spatio-temporal framework


ts_STD <- def.time(t.series=ns, segments=ny)


##Estimate the model using spTDyn package
#Note spT.Gibbs in spTimer gives the same error


GibbsDyn(gsp ~ pcap + hwy + water + util + pc , 
       data=Product_geo, model="GP", 
         time.data=ts_STD, 
         coords=~lon + lat,
          nItr=5000, nBurn=1000, report=1, tol.dist=0.05,
            distance.method="geodetic:km", cov.fnc="exponential", 
             
spatial.decay=decay(distribution="FIXED"),truncation.para=list(at=0,lambda=2))


#Also how to deal with unbalanced panel
#Delete some of the rows
Product_geo$cond = with(Product_geo,  if_else(state=="ALABAMA" & year==1971, 0,
                                         if_else(state=="COLORADO" & year==1971 
| year==1973 , 0,
                                         if_else(state=="TEXAS" & year==1971 | 
year==1973 | year==1985, 0, 1




Product_geo_unb <- Product_geo %>% filter(cond==1) %>% select(-cond)
glimpse(Product_geo_unb)


#How to use GibbsDyn or spT.Gibbs for such unbalanced panel data to estimate 
the Bayesian Gaussian Process (GP) Model?

___
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 when moving from PROJ4 to PROJ6

2020-07-28 Thread Gilberto Camara
Dear Roger 

I have installed the latest version of project, using “brew” as recommended by 
the PROJ website. I have also installed the latest versions of “sf” and “rgdal” 
as recommended by the “sf” GitHub. 

install.packages("rgdal", configure.args = c("--with-proj-lib=/usr/local/lib/", 
"--with-proj-include=/usr/local/include/“))

However, I still seeing the same environment for “sf” (proj version 6.3.1). Is 
there an additional command I need to do? 

Thanks
Gilberto


> On 28 Jul 2020, at 15:36, Gilberto Camara  
> wrote:
> 
> Dear Roger 
> 
> Please see my output:
> 
>> sf_extSoftVersion()
>  GEOS   GDAL proj.4 GDAL_with_GEOS USE_PROJ_H 
>   "3.8.1""3.1.1""6.3.1" "true" “true"
> 
> Thanks
> Gilberto
> 
> ===
> Prof Dr Gilberto Camara
> Secretariat Director
> GEO - Group on Earth Observations
> 7 bis, Avenue de La Paix
> CH-1211 Geneva - Switzerland
> Tel: +41227308480
> www.earthobservations.org
> 
>> On 28 Jul 2020, at 15:34, Roger Bivand  wrote:
>> 
>> sf_extSoftVersion()
> 
> 
>   [[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] Help when moving from PROJ4 to PROJ6

2020-07-28 Thread Gilberto Camara
Dear Roger 

Please see my output:

> sf_extSoftVersion()
  GEOS   GDAL proj.4 GDAL_with_GEOS USE_PROJ_H 
   "3.8.1""3.1.1""6.3.1" "true" “true"

Thanks
Gilberto

===
Prof Dr Gilberto Camara
Secretariat Director
GEO - Group on Earth Observations
7 bis, Avenue de La Paix
CH-1211 Geneva - Switzerland
Tel: +41227308480
www.earthobservations.org

> On 28 Jul 2020, at 15:34, Roger Bivand  wrote:
> 
> sf_extSoftVersion()


[[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 when moving from PROJ4 to PROJ6

2020-07-28 Thread Roger Bivand

On Tue, 28 Jul 2020, Gilberto Camara wrote:


Dear R-SIG-GEO (esp. Roger and Edzer)

I am having problems with “raster”, “rgdal”, and “sf” when moving from 
PROJ4 to PROJ6. Roger’s explanation on the r-spatial blog 
("https://www.r-spatial.org/r/2020/03/17/wkt.html”) and the rgdal blog 
(http://rgdal.r-forge.r-project.org/articles/PROJ6_GDAL3.html 
) are 
clear on the reasons why there are problems with CRS. As Roger points 
out, “package maintainers will need to review their use of crs objects”. 
So very true!


I appreciate the tremendous effort of Edzer and Roger for moving from 
PROJ4 to PROJ6.


However, I am failing to understand what is happening in the following 
example:



library(sf)


Could you please report:

sf_extSoftVersion()

Mine are (on Linux, own PROJ & GDAL installations):

sf_extSoftVersion()
  GEOS   GDAL proj.4 GDAL_with_GEOS USE_PROJ_H
   "3.8.1""3.1.2""7.1.0" "true" "true"

where there is no change in the coordinates (there should not be a change 
as sf::st_crs() only sets the CRS (but may swap the axes as per 
specification).


I see:


st_crs(ll_sfc2)

Coordinate Reference System:
  User input: +proj=longlat +datum=WGS84 +no_defs
  wkt:
GEOGCRS["unknown",
DATUM["World Geodetic System 1984",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]],
ID["EPSG",6326]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8901]],
CS[ellipsoidal,2],
AXIS["longitude",east,
ORDER[1],
ANGLEUNIT["degree",0.0174532925199433,
ID["EPSG",9122]]],
AXIS["latitude",north,
ORDER[2],
ANGLEUNIT["degree",0.0174532925199433,
ID["EPSG",9122

but


st_crs(ll_sfc)

Coordinate Reference System:
  User input: EPSG:4326
  wkt:
GEOGCRS["WGS 84",
DATUM["World Geodetic System 1984",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433]],
CS[ellipsoidal,2],
AXIS["geodetic latitude (Lat)",north,
ORDER[1],
ANGLEUNIT["degree",0.0174532925199433]],
AXIS["geodetic longitude (Lon)",east,
ORDER[2],
ANGLEUNIT["degree",0.0174532925199433]],
USAGE[
SCOPE["unknown"],
AREA["World"],
BBOX[-90,-180,90,180]],
ID["EPSG",4326]]

I can't see from 
https://www.r-spatial.org/r/2020/03/17/wkt.html#axis-order how to 
instantiate a crs object with non-authorized order.


In sp/rgdal:

sp <- SpatialPoints(cbind(longitude, latitude), 

proj4string=CRS("+proj=longlat +datum=WGS84"))

sp

SpatialPoints:
 longitude  latitude
[1,] -55.62277 -11.75932
Coordinate Reference System (CRS) arguments: +proj=longlat +datum=WGS84
+no_defs

cat(wkt(sp), "\n")

GEOGCRS["unknown",
DATUM["World Geodetic System 1984",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]],
ID["EPSG",6326]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8901]],
CS[ellipsoidal,2],
AXIS["longitude",east,
ORDER[1],
ANGLEUNIT["degree",0.0174532925199433,
ID["EPSG",9122]]],
AXIS["latitude",north,
ORDER[2],
ANGLEUNIT["degree",0.0174532925199433,
ID["EPSG",9122

sp2 <- SpatialPoints(cbind(longitude, latitude), 

proj4string=CRS(SRS_string="EPSG:4326"))

sp2

SpatialPoints:
 longitude  latitude
[1,] -55.62277 -11.75932
Coordinate Reference System (CRS) arguments: +proj=longlat +datum=WGS84
+no_defs

cat(wkt(sp2), "\n")

GEOGCRS["WGS 84",
DATUM["World Geodetic System 1984",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]],
ID["EPSG",6326]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8901]],
CS[ellipsoidal,2],
AXIS["longitude",east,
ORDER[1],
ANGLEUNIT["degree",0.0174532925199433,
ID["EPSG",9122]]],
AXIS["latitude",north,
ORDER[2],
ANGLEUNIT["degree",0.0174532925199433,
ID["EPSG",9122]]],
USAGE[
SCOPE["unknown"],
AREA["World"],
BBOX[-90,-180,90,180]]]

where sp/rgdal enforces legacy/GIS/visualization axis order. Coercing 
from the EPSG:4326 sp/rgdal object to sfc gives the intended order:



ll_sfc3 <- st_as_sfc(sp2)
ll_sfc3

Geometry set for 1 feature
geometry type:  POINT
dimension:  XY
bbox:   xmin: -55.62277 ymin: -11.75932 xmax: -55.62277 ymax: 
-11.75932

geographic CRS: WGS 84
POINT (-55.62277 -11.75932)

st_crs(ll_sfc3)

Coordinate Reference System:
  User input: WGS 84
  wkt:

[R-sig-Geo] Help when moving from PROJ4 to PROJ6

2020-07-28 Thread Gilberto Camara
Dear R-SIG-GEO (esp. Roger and Edzer)

I am having problems with “raster”, “rgdal”, and “sf” when moving from PROJ4 to 
PROJ6. Roger’s explanation on the r-spatial blog 
("https://www.r-spatial.org/r/2020/03/17/wkt.html”) and the rgdal blog 
(http://rgdal.r-forge.r-project.org/articles/PROJ6_GDAL3.html 
) are clear on 
the reasons why there are problems with CRS. As Roger points out, “package 
maintainers will need to review their use of crs objects”. So very true!

I appreciate the tremendous effort of Edzer and Roger for moving from PROJ4 to 
PROJ6. 

However, I am failing to understand what is happening in the following example:


library(sf)
> longitude <- -55.62277
> latitude  <- -11.75932

> st_point <- sf::st_point(c(longitude, latitude))
> ll_sfc   <- sf::st_sfc(st_point, crs = "EPSG:4326")

> ll_sfc[[1]]
POINT (-55.55527 -11.51782)

> ll_sfc2 <- sf::st_sfc(st_point, crs = "+proj=longlat +datum=WGS84 +no_defs”)

> ll_sfc2[[1]]
POINT (-55.62277 -11.75932)
==

> sessionInfo()
R version 4.0.1 (2020-06-06)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.5

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

other attached packages:
[1] sf_0.9-5  sits_0.9.5.1  raster_3.3-13 rgdal_1.5-12  sp_1.4-2
=

Why is using the EPSG code resulting in a different behaviour that using the 
old PROJ4 text?

Many thanks
Gilberto

===
Prof Dr Gilberto Camara
Secretariat Director
GEO - Group on Earth Observations
7 bis, Avenue de La Paix
CH-1211 Geneva - Switzerland
Tel: +41227308480
www.earthobservations.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 with universal kriging using gstat

2020-07-16 Thread Thomas Adams
Hi Roger,

Thank you... I finally figured out what I was doing wrong and have been
successful with gstat universal kriging. I will write-up the details for
others later today and plan to write a technical note of such for GRASS GIS
users, which I will submit there.

Best,
Tom

On Thu, Jul 16, 2020 at 4:15 AM Roger Bivand  wrote:

> On Wed, 15 Jul 2020, Thomas Adams wrote:
>
> > Hi all,
> >
> > It's been some time since I approached universal kriging using gstat (I
> > struggled with this previously, years ago:
> > https://stat.ethz.ch/pipermail/r-sig-geo/2006-May/001017.html).
> >
> > The problem...
> >
> > Within GRASS GIS, using R, I do this...
> >
> > (1) read a raster DEM into R from GRASS -- srtm <-
> > readRAST("mozambique_srtm_patch",cat=FALSE)
> > (2) read GRASS point data consisting of 4 fields (category, lon, lat,
> > temperature) -- airtemp <- readVECT("Mozambique_air_temp_2017_ann")
> > (3) so I have a SpatialGridDataFrame and SpatialPointsDataFrame,
> > respectively
> > (4) I can do the following: plot srtm, airtemp, generate an interpolated
> > grid of air temperatures with krige, using the airtemp
> > SpatialPointsDataFrame, and overlay the various data for visualization
> >
> > What I want to do is to use the srtm DEM data as a secondary trend
> variable
> > to spatially interpolate airtemp using universal kriging. I cannot figure
> > out how to construct the data sets and use krige in gstat to do this. I
> > have spent several days scouring the internet for an example (including
> > previous queries of my own, cited above) to no avail.
> >
> > It seems I should be able to do this, essentially:
> >
> > > dem<-read.asciigrid("gtopo30.dem")
> > > class(dem)
> > [1] "SpatialGridDataFrame"
> > attr(,"package")
> > [1] "sp"
> > > image(dem)
> > > points(Y ~ X, data=temps)
> > > class(temps)
> > [1] "data.frame"
> > > coordinates(temps)=~X+Y
> > > dem.ov=overlay(dem,temps)
> > > summary(dem.ov)
> >
> >> vgm <- vgm(psill=8,model="Exp",range=60,nugget=3.8)
> > > vgm_temps_r<-fit.variogram(variogram(T~gtopo30.dem,temps), model=vgm)
> > > plot(variogram(T~gtopo30.dem,temps),main = "fitted by gstat")
> > > temps_uk<-krige(T~gtopo30.dem,temps,dem, vgm_temps_r)
> > [using universal kriging]
> > > library(lattice)
> > > trellis.par.set(sp.theme())
> > > spplot(temps_uk,"var1.pred", main="Universal kriging predictions
> >
> > However, when I take this step:
> >
> >> dem.ov=overlay(srtm,airtemp)
> > Error in (function (classes, fdef, mtable)  :
> >  unable to find an inherited method for function ‘overlay’ for signature
> > ‘"SpatialGridDataFrame", "SpatialPointsDataFrame"’
>
> The overlay() method was retired long ago in favour of over(), and the
> order of the arguments was standardised. So over(airtemp, strm) should
> return the values of strm at the airtemp measuement points.
>
> Roger
>
> >
> >> airtemp$srtm.dem=dem.ov$srtm  <== this fails (see below)
> >
> >
> >> vgm <- vgm(psill=8,model="Exp",range=60,nugget=3.8)
> >> vgm_temps_r<-fit.variogram(variogram(temp~srtm.dem,airtemp), model=vgm)
> >> temps_uk<-krige(temp~srtm.dem,airtemp,srtm, vgm_temps_r)
> >
> >> airtemp$srtm.dem=srtm
> > Error in `[[<-.data.frame`(`*tmp*`, name, value =
> > new("SpatialGridDataFrame",  :
> >  replacement has 72821592 rows, data has 267
> >
> > Any suggestions?
> >
> > Best,
> > Tom
> >
> >
>
> --
> 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



-- 
Thomas E Adams, III
1724 Sage Lane
Blacksburg, VA 24060
tea...@gmail.com (personal)
t...@terrapredictions.org (work)

1 (513) 739-9512 (cell)

[[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 with universal kriging using gstat

2020-07-16 Thread Roger Bivand

On Wed, 15 Jul 2020, Thomas Adams wrote:


Hi all,

It's been some time since I approached universal kriging using gstat (I
struggled with this previously, years ago:
https://stat.ethz.ch/pipermail/r-sig-geo/2006-May/001017.html).

The problem...

Within GRASS GIS, using R, I do this...

(1) read a raster DEM into R from GRASS -- srtm <-
readRAST("mozambique_srtm_patch",cat=FALSE)
(2) read GRASS point data consisting of 4 fields (category, lon, lat,
temperature) -- airtemp <- readVECT("Mozambique_air_temp_2017_ann")
(3) so I have a SpatialGridDataFrame and SpatialPointsDataFrame,
respectively
(4) I can do the following: plot srtm, airtemp, generate an interpolated
grid of air temperatures with krige, using the airtemp
SpatialPointsDataFrame, and overlay the various data for visualization

What I want to do is to use the srtm DEM data as a secondary trend variable
to spatially interpolate airtemp using universal kriging. I cannot figure
out how to construct the data sets and use krige in gstat to do this. I
have spent several days scouring the internet for an example (including
previous queries of my own, cited above) to no avail.

It seems I should be able to do this, essentially:

> dem<-read.asciigrid("gtopo30.dem")
> class(dem)
[1] "SpatialGridDataFrame"
attr(,"package")
[1] "sp"
> image(dem)
> points(Y ~ X, data=temps)
> class(temps)
[1] "data.frame"
> coordinates(temps)=~X+Y
> dem.ov=overlay(dem,temps)
> summary(dem.ov)


vgm <- vgm(psill=8,model="Exp",range=60,nugget=3.8)

> vgm_temps_r<-fit.variogram(variogram(T~gtopo30.dem,temps), model=vgm)
> plot(variogram(T~gtopo30.dem,temps),main = "fitted by gstat")
> temps_uk<-krige(T~gtopo30.dem,temps,dem, vgm_temps_r)
[using universal kriging]
> library(lattice)
> trellis.par.set(sp.theme())
> spplot(temps_uk,"var1.pred", main="Universal kriging predictions

However, when I take this step:


dem.ov=overlay(srtm,airtemp)

Error in (function (classes, fdef, mtable)  :
 unable to find an inherited method for function ‘overlay’ for signature
‘"SpatialGridDataFrame", "SpatialPointsDataFrame"’


The overlay() method was retired long ago in favour of over(), and the 
order of the arguments was standardised. So over(airtemp, strm) should 
return the values of strm at the airtemp measuement points.


Roger




airtemp$srtm.dem=dem.ov$srtm  <== this fails (see below)




vgm <- vgm(psill=8,model="Exp",range=60,nugget=3.8)
vgm_temps_r<-fit.variogram(variogram(temp~srtm.dem,airtemp), model=vgm)
temps_uk<-krige(temp~srtm.dem,airtemp,srtm, vgm_temps_r)



airtemp$srtm.dem=srtm

Error in `[[<-.data.frame`(`*tmp*`, name, value =
new("SpatialGridDataFrame",  :
 replacement has 72821592 rows, data has 267

Any suggestions?

Best,
Tom




--
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


[R-sig-Geo] Help with universal kriging using gstat

2020-07-15 Thread Thomas Adams
Hi all,

It's been some time since I approached universal kriging using gstat (I
struggled with this previously, years ago:
https://stat.ethz.ch/pipermail/r-sig-geo/2006-May/001017.html).

The problem...

Within GRASS GIS, using R, I do this...

(1) read a raster DEM into R from GRASS -- srtm <-
readRAST("mozambique_srtm_patch",cat=FALSE)
(2) read GRASS point data consisting of 4 fields (category, lon, lat,
temperature) -- airtemp <- readVECT("Mozambique_air_temp_2017_ann")
(3) so I have a SpatialGridDataFrame and SpatialPointsDataFrame,
respectively
(4) I can do the following: plot srtm, airtemp, generate an interpolated
grid of air temperatures with krige, using the airtemp
SpatialPointsDataFrame, and overlay the various data for visualization

What I want to do is to use the srtm DEM data as a secondary trend variable
to spatially interpolate airtemp using universal kriging. I cannot figure
out how to construct the data sets and use krige in gstat to do this. I
have spent several days scouring the internet for an example (including
previous queries of my own, cited above) to no avail.

It seems I should be able to do this, essentially:

 > dem<-read.asciigrid("gtopo30.dem")
 > class(dem)
[1] "SpatialGridDataFrame"
attr(,"package")
[1] "sp"
 > image(dem)
 > points(Y ~ X, data=temps)
 > class(temps)
[1] "data.frame"
 > coordinates(temps)=~X+Y
 > dem.ov=overlay(dem,temps)
 > summary(dem.ov)

> vgm <- vgm(psill=8,model="Exp",range=60,nugget=3.8)
 > vgm_temps_r<-fit.variogram(variogram(T~gtopo30.dem,temps), model=vgm)
 > plot(variogram(T~gtopo30.dem,temps),main = "fitted by gstat")
 > temps_uk<-krige(T~gtopo30.dem,temps,dem, vgm_temps_r)
[using universal kriging]
 > library(lattice)
 > trellis.par.set(sp.theme())
 > spplot(temps_uk,"var1.pred", main="Universal kriging predictions

However, when I take this step:

> dem.ov=overlay(srtm,airtemp)
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function ‘overlay’ for signature
‘"SpatialGridDataFrame", "SpatialPointsDataFrame"’

> airtemp$srtm.dem=dem.ov$srtm  <== this fails (see below)


> vgm <- vgm(psill=8,model="Exp",range=60,nugget=3.8)
> vgm_temps_r<-fit.variogram(variogram(temp~srtm.dem,airtemp), model=vgm)
> temps_uk<-krige(temp~srtm.dem,airtemp,srtm, vgm_temps_r)

> airtemp$srtm.dem=srtm
Error in `[[<-.data.frame`(`*tmp*`, name, value =
new("SpatialGridDataFrame",  :
  replacement has 72821592 rows, data has 267

Any suggestions?

Best,
Tom

-- 
Thomas E Adams, III
1724 Sage Lane
Blacksburg, VA 24060
tea...@gmail.com (personal)
t...@terrapredictions.org (work)

1 (513) 739-9512 (cell)

[[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 with geocode() & get_map() please

2020-05-28 Thread Poling, William via R-sig-Geo
Hello again.

With Google help chat I discovered that I (we all) have a cloud billing Key and 
an API key.

I had everything correct in the cloud dashboard in terms of enabled API's, 
however, I was repeatedly trying to register the billing key and getting the 
errors after running the scripts, UGH!

register_google(key = "00-00-000AA0", write = TRUE) Billing Key NO GOOD
register_google(key = "Blahblah0BBLLAAHHblahlllaaabb00blah", write = TRUE) API 
Key from credentials GOOD

I hope this helps someone else down stream

Thank you Kent!

WHP

From: Kent Johnson  
Sent: Thursday, May 28, 2020 7:52 AM
To: r-sig-geo@r-project.org; Poling, William 
Subject: [EXTERNAL] Re: Help with geocode() & get_map() please

 External Email - Use Caution 
On Thu, May 28, 2020 at 6:03 AM <mailto:r-sig-geo-requ...@r-project.org> wrote:
Message: 1
Date: Wed, 27 May 2020 19:55:26 +
From: "Poling, William" <mailto:poli...@aetna.com>
Subject: [R-sig-Geo] Help with geocode()  & get_map() please
 
2. I am having trouble with get_map()

ny.map <- get_map("New York", zoom = 8)

Source : 
https://urldefense.proofpoint.com/v2/url?u=https-3A__maps.googleapis.com_maps_api_staticmap-3Fcenter-3DNew-2520York-26zoom-3D8-26size-3D640x640-26scale-3D2-26maptype-3Dterrain-26language-3Den-2DEN-26key-3D-5B012819-2D836529-2D634EA5-5D=DwMFaQ=wluqKIiwffOpZ6k5sqMWMBOn0vyYnlulRJmmvOXCFpM=j7MrcIQm2xjHa8v-2mTpmTCtKvneM2ExlYvnUWbsByY=CsMl9LHpa9ULoNXKdkrUT6ekC9fM5srAwGtqAbNgep0=l5KYIQUC-rz6VESNkigtwbi7rx-YYayVqIrdsrN0prE=
Error in aperm.default(map, c(2, 1, 3)) : 
invalid first argument, must be an array
In addition: Warning message:
In get_googlemap(center = location, zoom = zoom, maptype = maptype,  :
  HTTP 400 Bad Request 

This looks like the problem described here:
https://urldefense.proofpoint.com/v2/url?u=https-3A__github.com_dkahle_ggmap_issues_262=DwMFaQ=wluqKIiwffOpZ6k5sqMWMBOn0vyYnlulRJmmvOXCFpM=j7MrcIQm2xjHa8v-2mTpmTCtKvneM2ExlYvnUWbsByY=CsMl9LHpa9ULoNXKdkrUT6ekC9fM5srAwGtqAbNgep0=TegKIx-xo3fzI61Ul_ejBvccaNAV2c0cHSrQV5-5rNg=

It is a problem with your Google credentials. 

Kent 

Proprietary

NOTICE TO RECIPIENT OF INFORMATION:
This e-mail may contain confidential or privileged information. If you think 
you have received this e-mail in error, please advise the sender by reply 
e-mail and then delete this e-mail immediately.  
This e-mail may also contain protected health information (PHI) with 
information about sensitive medical conditions, including, but not limited to, 
treatment for substance use disorders, behavioral health, HIV/AIDS, or 
pregnancy. This type of information may be protected by various federal and/or 
state laws which prohibit any further disclosure without the express written 
consent of the person to whom it pertains or as otherwise permitted by law. Any 
unauthorized further disclosure may be considered a violation of federal and/or 
state law. A general authorization for the release of medical or other 
information may NOT be sufficient consent for release of this type of 
information.
Thank you. Aetna
___
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 with geocode() & get_map() please

2020-05-28 Thread Poling, William via R-sig-Geo
Ok, thank you, I suspected that and was unsure how to proceed beyond what I had 
described originally.

I will review your reference.

Thank you for your response Kent, much appreciated.

WHP

From: Kent Johnson  
Sent: Thursday, May 28, 2020 7:52 AM
To: r-sig-geo@r-project.org; Poling, William 
Subject: [EXTERNAL] Re: Help with geocode() & get_map() please

 External Email - Use Caution 
On Thu, May 28, 2020 at 6:03 AM <mailto:r-sig-geo-requ...@r-project.org> wrote:
Message: 1
Date: Wed, 27 May 2020 19:55:26 +
From: "Poling, William" <mailto:poli...@aetna.com>
Subject: [R-sig-Geo] Help with geocode()  & get_map() please
 
2. I am having trouble with get_map()

ny.map <- get_map("New York", zoom = 8)

Source : 
https://urldefense.proofpoint.com/v2/url?u=https-3A__maps.googleapis.com_maps_api_staticmap-3Fcenter-3DNew-2520York-26zoom-3D8-26size-3D640x640-26scale-3D2-26maptype-3Dterrain-26language-3Den-2DEN-26key-3D-5B012819-2D836529-2D634EA5-5D=DwMFaQ=wluqKIiwffOpZ6k5sqMWMBOn0vyYnlulRJmmvOXCFpM=j7MrcIQm2xjHa8v-2mTpmTCtKvneM2ExlYvnUWbsByY=CsMl9LHpa9ULoNXKdkrUT6ekC9fM5srAwGtqAbNgep0=l5KYIQUC-rz6VESNkigtwbi7rx-YYayVqIrdsrN0prE=
Error in aperm.default(map, c(2, 1, 3)) : 
invalid first argument, must be an array
In addition: Warning message:
In get_googlemap(center = location, zoom = zoom, maptype = maptype,  :
  HTTP 400 Bad Request 

This looks like the problem described here:
https://urldefense.proofpoint.com/v2/url?u=https-3A__github.com_dkahle_ggmap_issues_262=DwMFaQ=wluqKIiwffOpZ6k5sqMWMBOn0vyYnlulRJmmvOXCFpM=j7MrcIQm2xjHa8v-2mTpmTCtKvneM2ExlYvnUWbsByY=CsMl9LHpa9ULoNXKdkrUT6ekC9fM5srAwGtqAbNgep0=TegKIx-xo3fzI61Ul_ejBvccaNAV2c0cHSrQV5-5rNg=

It is a problem with your Google credentials. 

Kent 

Proprietary

NOTICE TO RECIPIENT OF INFORMATION:
This e-mail may contain confidential or privileged information. If you think 
you have received this e-mail in error, please advise the sender by reply 
e-mail and then delete this e-mail immediately.  
This e-mail may also contain protected health information (PHI) with 
information about sensitive medical conditions, including, but not limited to, 
treatment for substance use disorders, behavioral health, HIV/AIDS, or 
pregnancy. This type of information may be protected by various federal and/or 
state laws which prohibit any further disclosure without the express written 
consent of the person to whom it pertains or as otherwise permitted by law. Any 
unauthorized further disclosure may be considered a violation of federal and/or 
state law. A general authorization for the release of medical or other 
information may NOT be sufficient consent for release of this type of 
information.
Thank you. Aetna
___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


[R-sig-Geo] Help with geocode() & get_map() please

2020-05-27 Thread Poling, William via R-sig-Geo
Hello:

#RStudio Version Version 1.2.1335 
sessionInfo() 
# R version 4.0.0 Patched (2020-05-03 r78349)
#Platform: x86_64-w64-mingw32/x64 (64-bit)
#Running under: Windows 10 x64 (build 17763)

library(ggmap)
library(sp)
library(rgdal)
library(rgeos)


I am trying to follow along with this stack-reference and recreate the 
recommended solution, then apply my data
https://gis.stackexchange.com/questions/133693/geographic-heatmaps-with-concentric-circles-by-distance?rq=1


I hope I have provided enough information below to reproduce or identify my 
errors.

Thank you for any assistance.

1. I am having trouble with geocode() 

nyc <- geocode("New York")
No such file or directory failed to load external entity 
"http://maps.google.com/maps/api/geocode/xml?address=New+York=false;
Error : 1: No such file or directory2: failed to load external entity 
"http://maps.google.com/maps/api/geocode/xml?address=New+York=false;
Error in .geocode(xx$place, oneRecord = oneRecord, extent = extent, progress = 
progress) : 
  object 'doc' not found


AND


2. I am having trouble with get_map()

ny.map <- get_map("New York", zoom = 8)

Source : 
https://maps.googleapis.com/maps/api/staticmap?center=New%20York=8=640x640=2=terrain=en-EN=[012819-836529-634EA5]
Error in aperm.default(map, c(2, 1, 3)) : 
invalid first argument, must be an array
In addition: Warning message:
In get_googlemap(center = location, zoom = zoom, maptype = maptype,  :
  HTTP 400 Bad Request 

I have researched these errors and still do not seem to understand what I am 
doing wrong, or missing?

I have an API key and I believe I have initiated it correctly

I found this reference or a similar problem and followed the advice provided.
https://cran.r-project.org/web/packages/ggmap/ggmap.pdf


As suggested I went out to https://console.cloud.google.com/
and initiated suggested API's.

I manage to get through the next steps: 

#create the circles with gBuffer and then reproject them into WGS84 for ggmap.

# create spatialPoint object
coordinates(clus3) <- ~ lon + lat
proj4string(clus3) <- CRS("+init=epsg:4326")


# reproject to Google Mercator (meters)
clus3.mrc <- spTransform(clus3, CRS = CRS("+init=epsg:3857"))

# concentric rings (in miles):
dist.miles <-  seq(15, 25, 30)

# create a dataframe with the circle coordinates function
circ.df <- do.call(rbind,
   lapply(dist.miles, function(n) {
 circ <- gBuffer(clus3.mrc, width = n * 1609.344, 
quadsegs=20)
 circ.wgs <- spTransform(circ, CRS=CRS("+init=epsg:4326"))
 coords <- lapply(circ.wgs@polygons, function(x) 
{x@Polygons[[1]]@coords})
 data.frame(x=coords[[1]][,1], y=coords[[1]][,2], 
distance=n)
   }))

# text positions
text.pos <- cbind(aggregate( y ~ distance, data=circ.df, FUN=min), x=clus3$lon, 
row.names = NULL)


# fake a heatmap
set.seed(1)
xy2 <- data.frame(x=runif(100, -74.5, -73.5),y=runif(100, 40.2, 41.2))


But I can get no further at this point due to get_map():

# get basemap
#ny.map <- get_map("New York", zoom = 8) 
https://cran.r-project.org/web/packages/ggmap/ggmap.pdf
#Source : 
https://maps.googleapis.com/maps/api/staticmap?center=New%20York=8=640x640=2=terrain=en-EN=[012819-836529-634EA5]
Error in aperm.default(map, c(2, 1, 3)) : 
  invalid first argument, must be an array
In addition: Warning message:
In get_googlemap(center = location, zoom = zoom, maptype = maptype,  :
  HTTP 400 Bad Request

I tried to use this in the plot below and of course it errors out --#Error: 
ggmap plots objects of class ggmap, see ?get_map
ny.map <- ggplot2::map_data("state", region = c('new york', 'new jersey'))

ny.map <- get_map("state", region = c('new york', 'new jersey'))
#ERROR:
Source : 
https://maps.googleapis.com/maps/api/staticmap?center=state=10=640x640=2=terrain=en-EN=[012819-836529-634EA5]
Error in aperm.default(map, c(2, 1, 3)) : 
  invalid first argument, must be an array
In addition: Warning message:
In get_googlemap(center = location, zoom = zoom, maptype = maptype,  :
  HTTP 400 Bad Request

# ny.map <- map('state', region = c('new york', 'new jersey'),
# xlim=c(-74.12,-73.85), ylim=c(40.58,40.87)) 


# plot
ggmap(ny.map) + 
  stat_density2d(data=xy2, mapping=aes(x=x, y=y, fill=..level..), 
geom="polygon", alpha=0.2) +
  scale_fill_gradient(low = "blue", high = "red") +
  geom_path(data=circ.df, aes(x=x, y=y, group=distance), alpha=0.5) +
  geom_text(data=text.pos, aes(x=x, y=y, label=paste0(distance,"mi")))
#Error: ggmap plots objects of class ggmap, see ?get_map


#Here is the dataset I would like to use in the solution provided by this 
reference
https://gis.stackexchange.com/questions/133693/geographic-heatmaps-with-concentric-circles-by-distance?rq=1

dput(clus3)
new("SpatialPointsDataFrame", data = structure(list(ID = c(3L, 
57L, 87L, 141L, 173L, 286L, 287L, 335L, 553L, 574L, 598L, 634L, 
653L, 661L, 676L, 683L, 684L, 687L, 732L, 742L, 753L, 779L, 785L, 
793L, 798L, 

Re: [R-sig-Geo] Help with spTransform() function and final plot colors

2020-05-18 Thread Poling, William via R-sig-Geo

Thank you Michael this is very helpful. I see now where my trouble is, the EPSG.

Best regards.

WHP

From: Michael Sumner  
Sent: Monday, May 18, 2020 5:02 AM
To: Poling, William 
Cc: RsigGeo 
Subject: [EXTERNAL] Re: [R-sig-Geo] Help with spTransform() function and final 
plot colors

 External Email - Use Caution 
Hi, your longlat coordinates are in the western hemisphere (-119, 39) but EPSG 
27700 is designed for (and appropriate for some scenarios) somewhere in the UK. 
You need a local projection suitable for the area you are in. Look for an EPSG 
for your region, or maybe Albers conic or Lambert Azimuthal local authority 
(look on a paper map if you have one). Or define your own with projstrings (or 
wkt, it's a bit complicated atm to advise simple construction). There's some 
discussion here:
https://urldefense.proofpoint.com/v2/url?u=https-3A__geocompr.robinlovelace.net_reproj-2Dgeo-2Ddata.html-23which-2Dcrs-2Dto-2Duse=DwMFaQ=wluqKIiwffOpZ6k5sqMWMBOn0vyYnlulRJmmvOXCFpM=j7MrcIQm2xjHa8v-2mTpmTCtKvneM2ExlYvnUWbsByY=fDdQM1OwedGCkkG0UQTfAOUnp2_nUYnL-S_lSDHqxzM=bfYXSOc0JPxDRml-FQoxYoyDQ0nKdjPoNQrEE7yMzik=

Some will say use UTM, but you should not unless it's a particular local one 
used commonly in your work and the region the data is from.

HTH, Mike




On Mon., 18 May 2020, 19:46 Poling, William via R-sig-Geo, 
<mailto:r-sig-geo@r-project.org> wrote:
#RStudio Version Version 1.2.1335
sessionInfo()
# R version 4.0.0 Patched (2020-05-03 r78349)
#Platform: x86_64-w64-mingw32/x64 (64-bit) #Running under: Windows 10 x64 
(build 17763)

Hello. I am running my data through a routine I found that finds clusters of 
data points based on distance rule.
https://urldefense.proofpoint.com/v2/url?u=https-3A__gis.stackexchange.com_questions_64392_finding-2Dclusters-2Dof-2Dpoints-2Dbased-2Ddistance-2Drule-2Dusing-2Dr=DwMFaQ=wluqKIiwffOpZ6k5sqMWMBOn0vyYnlulRJmmvOXCFpM=j7MrcIQm2xjHa8v-2mTpmTCtKvneM2ExlYvnUWbsByY=fDdQM1OwedGCkkG0UQTfAOUnp2_nUYnL-S_lSDHqxzM=uZzRrl9yVqRTRQ2iHvphq2JK7UrTcUx61LL4r9ZLVEQ=

1. I get this error when I get to this point in the routine, see complete 
routine below?
xy <- spTransform(xy, CRS("+init=epsg:27700 +datum=WGS84")) non finite 
transformation detected:

I tried converting columns from numeric to Integer but did not help.

However, I continue to run the rest of the routine and the final sequence, the 
plot itself, seems to work Can this error be corrected somehow, despite the 
fact that it continues to work, just curious what it is I guess"

2. However in the plot at the end of the routine the color key appears with the 
colors but the clusters in the plot are black, see plot call at the end of the 
routine below?

Thank you for any advice.

WHP

ERROR:
non finite transformation detected:
      coords.x1 coords.x2        
 [1,] -119.7339  39.53939 Inf Inf
 [2,] -119.7665  39.39630 Inf Inf
 [3,] -119.7794  39.28768 Inf Inf
 [4,] -121.0234  39.20503 Inf Inf
 [5,] -122.0047  47.19262 Inf Inf
 [6,] -122.0135  47.18883 Inf Inf
 [7,] -122.0379  47.52190 Inf Inf
 [8,] -122.0578  47.60975 Inf Inf
 [9,] -122.1330  47.13669 Inf Inf
[10,] -122.1509  47.55962 Inf Inf
[11,] -122.1706  47.15546 Inf Inf
[12,] -122.1846  47.23485 Inf Inf
[13,] -122.1846  48.15307 Inf Inf
[14,] -122.1851  47.44870 Inf Inf
[15,] -122.1954  47.68485 Inf Inf
[16,] -122.1990  47.51610 Inf Inf
[17,] -122.2014  47.44772 Inf Inf
[18,] -122.2025  47.69815 Inf Inf
[19,] -122.2037  47.67190 Inf Inf
[20,] -122.2090  47.40378 Inf Inf
[21,] -122.2108  47.25336 Inf Inf
[22,] -122.2291  47.63880 Inf Inf
[23,] -122.2419  47.76870 Inf Inf
[24,] -122.2722  48.04803 Inf Inf
[25,] -122.2732  47.87700 Inf Inf
[26,] -122.2804  47.77620 Inf Inf
[27,] -122.2839  47.82103 Inf Inf
[28,] -122.2890  47.86899 Inf Inf
[29,] -122.2993  47.67306 Inf Inf
[30,] -122.3180  47.38217 Inf Inf
[31,] -122.3270  47.40378 Inf Inf
[32,] -122.3474  47.43884 Inf Inf
[33,] -122.3484  47.53083 Inf Inf
[34,] -122.3581  47.27678 Inf Inf
[35,] -122.3618  47.76735 Inf Inf
[36,] -122.3700  47.56567 Inf Inf
[37,] -122.3908  47.54938 Inf Inf
[38,] -122.4128  47.64622 Inf Inf
[39,] -122.4293  47.17660 Inf Inf
[40,] -122.4621  47.44505 Inf Inf
[41,] -122.4904  47.27460 Inf Inf
[42,] -122.5515  46.93979 Inf Inf
[43,] -122.7348  42.37320 Inf Inf
[44,] -122.7827  47.31059 Inf Inf
[45,] -122.7987  47.23475 Inf Inf
[46,] -122.8385  42.35119 Inf Inf
[47,] -122.8537  42.34495 Inf Inf
[48,] -122.8904  42.39555 Inf Inf
[49,] -122.8927  42.33022 Inf Inf
[50,] -122.9451  47.37574 Inf Inf
[51,] -122.9594  42.30376 Inf Inf
[52,] -123.0641  47.16428 Inf Inf
[53,] -123.3413  42.44117 Inf Inf
Error in spTransform(xSP, CRSobj, ...) : 
  failure in points 
1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25:26:27:28:29:30:31:32:33:34:35:36:37:38:39:40:41:42:43:44:45:46:47:48:49:50:51:52:53
In addition: Warning message:
In spTransform(xSP, CRSobj, ...) : 53 projected point(s) not finite

Here is the data:
dput(sample)
structure(list(ID = 1:53, L

Re: [R-sig-Geo] Help with spTransform() function and final plot colors

2020-05-18 Thread Roger Bivand
This messy thread was on R-help first, and comes from a corporation able 
to pay for consulting help. It contains no reproducible example, and 
"+init=epsg:27700 +datum=WGS84" qualifies to fail GIS001 (the datum of 
OSGB is NOT WGS84, the same evident blunder is in the copied SO 
"code"). No mention is made of the versions of the packages used (as 
printed to the console when rgdal is loaded or from 
rgdal::extSoftVersion(), and no motivation is given.


If the OP really needs assistance, this list expects a fully reproducible 
example using a built-in data set - the SO query seems to refer to Meuse.


Roger

On Mon, 18 May 2020, Poling, William via R-sig-Geo wrote:


Hello, I have found an additional problem.

I should be getting 3 columns back in the xy@data at some point.
$ ID   : int  1 2 3 4 5 6 7 8 9 10 ...
# $ Clust  : int  1 1 1 1 1 1 1 1 1 1 ... This is always - 1
# $ Clust.1   : int  1 1 1 1 1 1 1 1 1 1 ... This would be the 
cluster number, like 1-3, I am not getting this column back?


Yet the plot runs and indicates three different clusters?



WHP


Proprietary

-Original Message-
From: Poling, William 
Sent: Monday, May 18, 2020 4:47 AM
To: r-sig-geo@r-project.org
Cc: Poling, William 
Subject: RE: Help with spTransform() function and final plot colors

Hello, I have found an additional problem.

I should be getting 3 columns back in the xy@data at some point.
$ ID   : int  1 2 3 4 5 6 7 8 9 10 ...
# $ Clust  : int  1 1 1 1 1 1 1 1 1 1 ... This is always - 1
# $ Clust.1   : int  1 1 1 1 1 1 1 1 1 1 ... This would be the 
cluster number, like 1-3, I am not getting this column back?


Yet the plot runs and indicates three different clusters?



WHP



Proprietary

-Original Message-
From: Poling, William 
Sent: Monday, May 18, 2020 4:46 AM
To: r-sig-geo@r-project.org
Cc: Poling, William 
Subject: Help with spTransform() function and final plot colors

#RStudio Version Version 1.2.1335
sessionInfo()
# R version 4.0.0 Patched (2020-05-03 r78349)
#Platform: x86_64-w64-mingw32/x64 (64-bit) #Running under: Windows 10 x64 
(build 17763)

Hello. I am running my data through a routine I found that finds clusters of 
data points based on distance rule.
https://gis.stackexchange.com/questions/64392/finding-clusters-of-points-based-distance-rule-using-r

1. I get this error when I get to this point in the routine, see complete 
routine below?
xy <- spTransform(xy, CRS("+init=epsg:27700 +datum=WGS84")) non finite 
transformation detected:

I tried converting columns from numeric to Integer but did not help.

However, I continue to run the rest of the routine and the final sequence, the plot 
itself, seems to work Can this error be corrected somehow, despite the fact that it 
continues to work, just curious what it is I guess"

2. However in the plot at the end of the routine the color key appears with the 
colors but the clusters in the plot are black, see plot call at the end of the 
routine below?

Thank you for any advice.

WHP

ERROR:
non finite transformation detected:
 coords.x1 coords.x2
[1,] -119.7339  39.53939 Inf Inf
[2,] -119.7665  39.39630 Inf Inf
[3,] -119.7794  39.28768 Inf Inf
[4,] -121.0234  39.20503 Inf Inf
[5,] -122.0047  47.19262 Inf Inf
[6,] -122.0135  47.18883 Inf Inf
[7,] -122.0379  47.52190 Inf Inf
[8,] -122.0578  47.60975 Inf Inf
[9,] -122.1330  47.13669 Inf Inf
[10,] -122.1509  47.55962 Inf Inf
[11,] -122.1706  47.15546 Inf Inf
[12,] -122.1846  47.23485 Inf Inf
[13,] -122.1846  48.15307 Inf Inf
[14,] -122.1851  47.44870 Inf Inf
[15,] -122.1954  47.68485 Inf Inf
[16,] -122.1990  47.51610 Inf Inf
[17,] -122.2014  47.44772 Inf Inf
[18,] -122.2025  47.69815 Inf Inf
[19,] -122.2037  47.67190 Inf Inf
[20,] -122.2090  47.40378 Inf Inf
[21,] -122.2108  47.25336 Inf Inf
[22,] -122.2291  47.63880 Inf Inf
[23,] -122.2419  47.76870 Inf Inf
[24,] -122.2722  48.04803 Inf Inf
[25,] -122.2732  47.87700 Inf Inf
[26,] -122.2804  47.77620 Inf Inf
[27,] -122.2839  47.82103 Inf Inf
[28,] -122.2890  47.86899 Inf Inf
[29,] -122.2993  47.67306 Inf Inf
[30,] -122.3180  47.38217 Inf Inf
[31,] -122.3270  47.40378 Inf Inf
[32,] -122.3474  47.43884 Inf Inf
[33,] -122.3484  47.53083 Inf Inf
[34,] -122.3581  47.27678 Inf Inf
[35,] -122.3618  47.76735 Inf Inf
[36,] -122.3700  47.56567 Inf Inf
[37,] -122.3908  47.54938 Inf Inf
[38,] -122.4128  47.64622 Inf Inf
[39,] -122.4293  47.17660 Inf Inf
[40,] -122.4621  47.44505 Inf Inf
[41,] -122.4904  47.27460 Inf Inf
[42,] -122.5515  46.93979 Inf Inf
[43,] -122.7348  42.37320 Inf Inf
[44,] -122.7827  47.31059 Inf Inf
[45,] -122.7987  47.23475 Inf Inf
[46,] -122.8385  42.35119 Inf Inf
[47,] -122.8537  42.34495 Inf Inf
[48,] -122.8904  42.39555 Inf Inf
[49,] -122.8927  42.33022 Inf Inf
[50,] -122.9451  47.37574 Inf Inf
[51,] -122.9594  42.30376 Inf Inf
[52,] -123.0641  47.16428 Inf Inf
[53,] -123.3413  42.44117 Inf Inf
Error in spTransform(xSP, 

Re: [R-sig-Geo] Help with spTransform() function and final plot colors

2020-05-18 Thread Michael Sumner
Hi, your longlat coordinates are in the western hemisphere (-119, 39) but
EPSG 27700 is designed for (and appropriate for some scenarios) somewhere
in the UK. You need a local projection suitable for the area you are in.
Look for an EPSG for your region, or maybe Albers conic or Lambert
Azimuthal local authority (look on a paper map if you have one). Or define
your own with projstrings (or wkt, it's a bit complicated atm to advise
simple construction). There's some discussion here:
https://geocompr.robinlovelace.net/reproj-geo-data.html#which-crs-to-use

Some will say use UTM, but you should not unless it's a particular local
one used commonly in your work and the region the data is from.

HTH, Mike





On Mon., 18 May 2020, 19:46 Poling, William via R-sig-Geo, <
r-sig-geo@r-project.org> wrote:

> #RStudio Version Version 1.2.1335
> sessionInfo()
> # R version 4.0.0 Patched (2020-05-03 r78349)
> #Platform: x86_64-w64-mingw32/x64 (64-bit) #Running under: Windows 10 x64
> (build 17763)
>
> Hello. I am running my data through a routine I found that finds clusters
> of data points based on distance rule.
>
> https://gis.stackexchange.com/questions/64392/finding-clusters-of-points-based-distance-rule-using-r
>
> 1. I get this error when I get to this point in the routine, see complete
> routine below?
> xy <- spTransform(xy, CRS("+init=epsg:27700 +datum=WGS84")) non finite
> transformation detected:
>
> I tried converting columns from numeric to Integer but did not help.
>
> However, I continue to run the rest of the routine and the final sequence,
> the plot itself, seems to work Can this error be corrected somehow, despite
> the fact that it continues to work, just curious what it is I guess"
>
> 2. However in the plot at the end of the routine the color key appears
> with the colors but the clusters in the plot are black, see plot call at
> the end of the routine below?
>
> Thank you for any advice.
>
> WHP
>
> ERROR:
> non finite transformation detected:
>   coords.x1 coords.x2
>  [1,] -119.7339  39.53939 Inf Inf
>  [2,] -119.7665  39.39630 Inf Inf
>  [3,] -119.7794  39.28768 Inf Inf
>  [4,] -121.0234  39.20503 Inf Inf
>  [5,] -122.0047  47.19262 Inf Inf
>  [6,] -122.0135  47.18883 Inf Inf
>  [7,] -122.0379  47.52190 Inf Inf
>  [8,] -122.0578  47.60975 Inf Inf
>  [9,] -122.1330  47.13669 Inf Inf
> [10,] -122.1509  47.55962 Inf Inf
> [11,] -122.1706  47.15546 Inf Inf
> [12,] -122.1846  47.23485 Inf Inf
> [13,] -122.1846  48.15307 Inf Inf
> [14,] -122.1851  47.44870 Inf Inf
> [15,] -122.1954  47.68485 Inf Inf
> [16,] -122.1990  47.51610 Inf Inf
> [17,] -122.2014  47.44772 Inf Inf
> [18,] -122.2025  47.69815 Inf Inf
> [19,] -122.2037  47.67190 Inf Inf
> [20,] -122.2090  47.40378 Inf Inf
> [21,] -122.2108  47.25336 Inf Inf
> [22,] -122.2291  47.63880 Inf Inf
> [23,] -122.2419  47.76870 Inf Inf
> [24,] -122.2722  48.04803 Inf Inf
> [25,] -122.2732  47.87700 Inf Inf
> [26,] -122.2804  47.77620 Inf Inf
> [27,] -122.2839  47.82103 Inf Inf
> [28,] -122.2890  47.86899 Inf Inf
> [29,] -122.2993  47.67306 Inf Inf
> [30,] -122.3180  47.38217 Inf Inf
> [31,] -122.3270  47.40378 Inf Inf
> [32,] -122.3474  47.43884 Inf Inf
> [33,] -122.3484  47.53083 Inf Inf
> [34,] -122.3581  47.27678 Inf Inf
> [35,] -122.3618  47.76735 Inf Inf
> [36,] -122.3700  47.56567 Inf Inf
> [37,] -122.3908  47.54938 Inf Inf
> [38,] -122.4128  47.64622 Inf Inf
> [39,] -122.4293  47.17660 Inf Inf
> [40,] -122.4621  47.44505 Inf Inf
> [41,] -122.4904  47.27460 Inf Inf
> [42,] -122.5515  46.93979 Inf Inf
> [43,] -122.7348  42.37320 Inf Inf
> [44,] -122.7827  47.31059 Inf Inf
> [45,] -122.7987  47.23475 Inf Inf
> [46,] -122.8385  42.35119 Inf Inf
> [47,] -122.8537  42.34495 Inf Inf
> [48,] -122.8904  42.39555 Inf Inf
> [49,] -122.8927  42.33022 Inf Inf
> [50,] -122.9451  47.37574 Inf Inf
> [51,] -122.9594  42.30376 Inf Inf
> [52,] -123.0641  47.16428 Inf Inf
> [53,] -123.3413  42.44117 Inf Inf
> Error in spTransform(xSP, CRSobj, ...) :
>   failure in points
> 1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25:26:27:28:29:30:31:32:33:34:35:36:37:38:39:40:41:42:43:44:45:46:47:48:49:50:51:52:53
> In addition: Warning message:
> In spTransform(xSP, CRSobj, ...) : 53 projected point(s) not finite
>
> Here is the data:
> dput(sample)
> structure(list(ID = 1:53, Longitude = c(-119.733899, -119.766493,
> -119.779416, -121.0234, -122.004736, -122.013456, -122.0379, -122.0578,
> -122.132971, -122.150901, -122.170608, -122.18462, -122.184639,
> -122.185079, -122.195398, -122.198994, -122.201356, -122.202507,
> -122.20371, -122.209047, -122.210797, -122.229095, -122.2419, -122.27216,
> -122.273164, -122.280355, -122.28389, -122.289043, -122.299261,
> -122.318009, -122.326987, -122.347382, -122.34844, -122.358115,
> -122.361839, -122.37003, -122.390815, -122.41282, -122.429323, -122.462136,
> -122.490417, -122.551483, -122.734847, -122.782736, -122.798669,
> -122.838498, -122.853683, -122.8904, -122.89271, -122.94511, -122.959407,
> 

Re: [R-sig-Geo] Help with spTransform() function and final plot colors

2020-05-18 Thread Poling, William via R-sig-Geo
Hello again.

I also found this discussion on non-finite transformation error, however, I am 
not sure what to look for in the output after I apply my data?

https://stackoverflow.com/questions/14880294/non-finite-transformation-detected-in-sptransform-in-rgdal-r-package



str(sample)
GPS.Points <- sample[,c(2,3)]

n_chunks <- 3 #number of pieces you will break you data into n.points <- 
dim(GPS.Points)[1] breaks <- seq(1,n.points, by=round(n.points/n_chunks)) 
breaks <- c(breaks, n.points) #make sure to include last points as well

i=1
for (i in 1:(length(breaks)-1)){
  cat('\n','converting points', breaks[i], "to", breaks[i+1])
  temp.GPS.Points=GPS.Points[breaks[i]:breaks[i+1],]
  temp.GPS.Points.Spatial.Data <- SpatialPoints(temp.GPS.Points, 
proj4string=CRS("+proj=longlat 
+ellps=WGS84"))
  temp.GPS.Points.UTM.Spatial.Data <- spTransform(temp.GPS.Points.Spatial.Data,
  CRS("+proj=utm +south 
+zone=34 
+ellps=WGS84"))
}

Thank you for any advice.

WHP


Proprietary

-Original Message-
From: Poling, William  
Sent: Monday, May 18, 2020 4:47 AM
To: r-sig-geo@r-project.org
Cc: Poling, William 
Subject: RE: Help with spTransform() function and final plot colors

Hello, I have found an additional problem.

I should be getting 3 columns back in the xy@data at some point.
$ ID   : int  1 2 3 4 5 6 7 8 9 10 ...
# $ Clust  : int  1 1 1 1 1 1 1 1 1 1 ... This is always - 1
# $ Clust.1   : int  1 1 1 1 1 1 1 1 1 1 ... This would be the 
cluster number, like 1-3, I am not getting this column back?


Yet the plot runs and indicates three different clusters?



WHP



Proprietary

-Original Message-
From: Poling, William  
Sent: Monday, May 18, 2020 4:46 AM
To: r-sig-geo@r-project.org
Cc: Poling, William 
Subject: Help with spTransform() function and final plot colors

#RStudio Version Version 1.2.1335
sessionInfo()
# R version 4.0.0 Patched (2020-05-03 r78349)
#Platform: x86_64-w64-mingw32/x64 (64-bit) #Running under: Windows 10 x64 
(build 17763)

Hello. I am running my data through a routine I found that finds clusters of 
data points based on distance rule.
https://gis.stackexchange.com/questions/64392/finding-clusters-of-points-based-distance-rule-using-r

1. I get this error when I get to this point in the routine, see complete 
routine below?
xy <- spTransform(xy, CRS("+init=epsg:27700 +datum=WGS84")) non finite 
transformation detected:

I tried converting columns from numeric to Integer but did not help.

However, I continue to run the rest of the routine and the final sequence, the 
plot itself, seems to work Can this error be corrected somehow, despite the 
fact that it continues to work, just curious what it is I guess"

2. However in the plot at the end of the routine the color key appears with the 
colors but the clusters in the plot are black, see plot call at the end of the 
routine below?

Thank you for any advice.

WHP

ERROR:
non finite transformation detected:
  coords.x1 coords.x2
 [1,] -119.7339  39.53939 Inf Inf
 [2,] -119.7665  39.39630 Inf Inf
 [3,] -119.7794  39.28768 Inf Inf
 [4,] -121.0234  39.20503 Inf Inf
 [5,] -122.0047  47.19262 Inf Inf
 [6,] -122.0135  47.18883 Inf Inf
 [7,] -122.0379  47.52190 Inf Inf
 [8,] -122.0578  47.60975 Inf Inf
 [9,] -122.1330  47.13669 Inf Inf
[10,] -122.1509  47.55962 Inf Inf
[11,] -122.1706  47.15546 Inf Inf
[12,] -122.1846  47.23485 Inf Inf
[13,] -122.1846  48.15307 Inf Inf
[14,] -122.1851  47.44870 Inf Inf
[15,] -122.1954  47.68485 Inf Inf
[16,] -122.1990  47.51610 Inf Inf
[17,] -122.2014  47.44772 Inf Inf
[18,] -122.2025  47.69815 Inf Inf
[19,] -122.2037  47.67190 Inf Inf
[20,] -122.2090  47.40378 Inf Inf
[21,] -122.2108  47.25336 Inf Inf
[22,] -122.2291  47.63880 Inf Inf
[23,] -122.2419  47.76870 Inf Inf
[24,] -122.2722  48.04803 Inf Inf
[25,] -122.2732  47.87700 Inf Inf
[26,] -122.2804  47.77620 Inf Inf
[27,] -122.2839  47.82103 Inf Inf
[28,] -122.2890  47.86899 Inf Inf
[29,] -122.2993  47.67306 Inf Inf
[30,] -122.3180  47.38217 Inf Inf
[31,] -122.3270  47.40378 Inf Inf
[32,] -122.3474  47.43884 Inf Inf
[33,] -122.3484  47.53083 Inf Inf
[34,] -122.3581  47.27678 Inf Inf
[35,] -122.3618  47.76735 Inf Inf
[36,] -122.3700  47.56567 Inf Inf
[37,] -122.3908  47.54938 Inf Inf
[38,] -122.4128  47.64622 Inf Inf
[39,] -122.4293  47.17660 Inf Inf
[40,] -122.4621  47.44505 Inf Inf
[41,] -122.4904  47.27460 Inf Inf
[42,] -122.5515  46.93979 Inf Inf
[43,] -122.7348  42.37320 Inf Inf
[44,] -122.7827  47.31059 Inf Inf
[45,] -122.7987  47.23475 Inf Inf
[46,] -122.8385  42.35119 Inf Inf
[47,] -122.8537  42.34495 Inf Inf
[48,] -122.8904  42.39555 Inf Inf
[49,] -122.8927  42.33022 Inf Inf
[50,] -122.9451  47.37574 Inf Inf
[51,] -122.9594  42.30376 Inf Inf
[52,] -123.0641  47.16428 Inf Inf
[53,] -123.3413  42.44117 Inf Inf
Error in spTransform(xSP, CRSobj, ...) : 
  failure in points 

Re: [R-sig-Geo] Help with spTransform() function and final plot colors

2020-05-18 Thread Poling, William via R-sig-Geo
Hello, I have found an additional problem.

I should be getting 3 columns back in the xy@data at some point.
$ ID   : int  1 2 3 4 5 6 7 8 9 10 ...
# $ Clust  : int  1 1 1 1 1 1 1 1 1 1 ... This is always - 1
# $ Clust.1   : int  1 1 1 1 1 1 1 1 1 1 ... This would be the 
cluster number, like 1-3, I am not getting this column back?


Yet the plot runs and indicates three different clusters?



WHP


Proprietary

-Original Message-
From: Poling, William  
Sent: Monday, May 18, 2020 4:47 AM
To: r-sig-geo@r-project.org
Cc: Poling, William 
Subject: RE: Help with spTransform() function and final plot colors

Hello, I have found an additional problem.

I should be getting 3 columns back in the xy@data at some point.
$ ID   : int  1 2 3 4 5 6 7 8 9 10 ...
# $ Clust  : int  1 1 1 1 1 1 1 1 1 1 ... This is always - 1
# $ Clust.1   : int  1 1 1 1 1 1 1 1 1 1 ... This would be the 
cluster number, like 1-3, I am not getting this column back?


Yet the plot runs and indicates three different clusters?



WHP



Proprietary

-Original Message-
From: Poling, William  
Sent: Monday, May 18, 2020 4:46 AM
To: r-sig-geo@r-project.org
Cc: Poling, William 
Subject: Help with spTransform() function and final plot colors

#RStudio Version Version 1.2.1335
sessionInfo()
# R version 4.0.0 Patched (2020-05-03 r78349)
#Platform: x86_64-w64-mingw32/x64 (64-bit) #Running under: Windows 10 x64 
(build 17763)

Hello. I am running my data through a routine I found that finds clusters of 
data points based on distance rule.
https://gis.stackexchange.com/questions/64392/finding-clusters-of-points-based-distance-rule-using-r

1. I get this error when I get to this point in the routine, see complete 
routine below?
xy <- spTransform(xy, CRS("+init=epsg:27700 +datum=WGS84")) non finite 
transformation detected:

I tried converting columns from numeric to Integer but did not help.

However, I continue to run the rest of the routine and the final sequence, the 
plot itself, seems to work Can this error be corrected somehow, despite the 
fact that it continues to work, just curious what it is I guess"

2. However in the plot at the end of the routine the color key appears with the 
colors but the clusters in the plot are black, see plot call at the end of the 
routine below?

Thank you for any advice.

WHP

ERROR:
non finite transformation detected:
  coords.x1 coords.x2
 [1,] -119.7339  39.53939 Inf Inf
 [2,] -119.7665  39.39630 Inf Inf
 [3,] -119.7794  39.28768 Inf Inf
 [4,] -121.0234  39.20503 Inf Inf
 [5,] -122.0047  47.19262 Inf Inf
 [6,] -122.0135  47.18883 Inf Inf
 [7,] -122.0379  47.52190 Inf Inf
 [8,] -122.0578  47.60975 Inf Inf
 [9,] -122.1330  47.13669 Inf Inf
[10,] -122.1509  47.55962 Inf Inf
[11,] -122.1706  47.15546 Inf Inf
[12,] -122.1846  47.23485 Inf Inf
[13,] -122.1846  48.15307 Inf Inf
[14,] -122.1851  47.44870 Inf Inf
[15,] -122.1954  47.68485 Inf Inf
[16,] -122.1990  47.51610 Inf Inf
[17,] -122.2014  47.44772 Inf Inf
[18,] -122.2025  47.69815 Inf Inf
[19,] -122.2037  47.67190 Inf Inf
[20,] -122.2090  47.40378 Inf Inf
[21,] -122.2108  47.25336 Inf Inf
[22,] -122.2291  47.63880 Inf Inf
[23,] -122.2419  47.76870 Inf Inf
[24,] -122.2722  48.04803 Inf Inf
[25,] -122.2732  47.87700 Inf Inf
[26,] -122.2804  47.77620 Inf Inf
[27,] -122.2839  47.82103 Inf Inf
[28,] -122.2890  47.86899 Inf Inf
[29,] -122.2993  47.67306 Inf Inf
[30,] -122.3180  47.38217 Inf Inf
[31,] -122.3270  47.40378 Inf Inf
[32,] -122.3474  47.43884 Inf Inf
[33,] -122.3484  47.53083 Inf Inf
[34,] -122.3581  47.27678 Inf Inf
[35,] -122.3618  47.76735 Inf Inf
[36,] -122.3700  47.56567 Inf Inf
[37,] -122.3908  47.54938 Inf Inf
[38,] -122.4128  47.64622 Inf Inf
[39,] -122.4293  47.17660 Inf Inf
[40,] -122.4621  47.44505 Inf Inf
[41,] -122.4904  47.27460 Inf Inf
[42,] -122.5515  46.93979 Inf Inf
[43,] -122.7348  42.37320 Inf Inf
[44,] -122.7827  47.31059 Inf Inf
[45,] -122.7987  47.23475 Inf Inf
[46,] -122.8385  42.35119 Inf Inf
[47,] -122.8537  42.34495 Inf Inf
[48,] -122.8904  42.39555 Inf Inf
[49,] -122.8927  42.33022 Inf Inf
[50,] -122.9451  47.37574 Inf Inf
[51,] -122.9594  42.30376 Inf Inf
[52,] -123.0641  47.16428 Inf Inf
[53,] -123.3413  42.44117 Inf Inf
Error in spTransform(xSP, CRSobj, ...) : 
  failure in points 
1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25:26:27:28:29:30:31:32:33:34:35:36:37:38:39:40:41:42:43:44:45:46:47:48:49:50:51:52:53
In addition: Warning message:
In spTransform(xSP, CRSobj, ...) : 53 projected point(s) not finite

Here is the data:
dput(sample)
structure(list(ID = 1:53, Longitude = c(-119.733899, -119.766493, -119.779416, 
-121.0234, -122.004736, -122.013456, -122.0379, -122.0578, -122.132971, 
-122.150901, -122.170608, -122.18462, -122.184639, -122.185079, -122.195398, 
-122.198994, -122.201356, -122.202507, -122.20371, -122.209047, -122.210797, 
-122.229095, -122.2419, -122.27216, 

Re: [R-sig-Geo] Help with spTransform() function and final plot colors

2020-05-18 Thread Poling, William via R-sig-Geo
Hello, I have found an additional problem.

I should be getting 3 columns back in the xy@data at some point.
$ ID   : int  1 2 3 4 5 6 7 8 9 10 ...
# $ Clust  : int  1 1 1 1 1 1 1 1 1 1 ... This is always - 1
# $ Clust.1   : int  1 1 1 1 1 1 1 1 1 1 ... This would be the 
cluster number, like 1-3, I am not getting this column back?


Yet the plot runs and indicates three different clusters?



WHP



Proprietary

-Original Message-
From: Poling, William  
Sent: Monday, May 18, 2020 4:46 AM
To: r-sig-geo@r-project.org
Cc: Poling, William 
Subject: Help with spTransform() function and final plot colors

#RStudio Version Version 1.2.1335
sessionInfo()
# R version 4.0.0 Patched (2020-05-03 r78349)
#Platform: x86_64-w64-mingw32/x64 (64-bit) #Running under: Windows 10 x64 
(build 17763)

Hello. I am running my data through a routine I found that finds clusters of 
data points based on distance rule.
https://gis.stackexchange.com/questions/64392/finding-clusters-of-points-based-distance-rule-using-r

1. I get this error when I get to this point in the routine, see complete 
routine below?
xy <- spTransform(xy, CRS("+init=epsg:27700 +datum=WGS84")) non finite 
transformation detected:

I tried converting columns from numeric to Integer but did not help.

However, I continue to run the rest of the routine and the final sequence, the 
plot itself, seems to work Can this error be corrected somehow, despite the 
fact that it continues to work, just curious what it is I guess"

2. However in the plot at the end of the routine the color key appears with the 
colors but the clusters in the plot are black, see plot call at the end of the 
routine below?

Thank you for any advice.

WHP

ERROR:
non finite transformation detected:
  coords.x1 coords.x2
 [1,] -119.7339  39.53939 Inf Inf
 [2,] -119.7665  39.39630 Inf Inf
 [3,] -119.7794  39.28768 Inf Inf
 [4,] -121.0234  39.20503 Inf Inf
 [5,] -122.0047  47.19262 Inf Inf
 [6,] -122.0135  47.18883 Inf Inf
 [7,] -122.0379  47.52190 Inf Inf
 [8,] -122.0578  47.60975 Inf Inf
 [9,] -122.1330  47.13669 Inf Inf
[10,] -122.1509  47.55962 Inf Inf
[11,] -122.1706  47.15546 Inf Inf
[12,] -122.1846  47.23485 Inf Inf
[13,] -122.1846  48.15307 Inf Inf
[14,] -122.1851  47.44870 Inf Inf
[15,] -122.1954  47.68485 Inf Inf
[16,] -122.1990  47.51610 Inf Inf
[17,] -122.2014  47.44772 Inf Inf
[18,] -122.2025  47.69815 Inf Inf
[19,] -122.2037  47.67190 Inf Inf
[20,] -122.2090  47.40378 Inf Inf
[21,] -122.2108  47.25336 Inf Inf
[22,] -122.2291  47.63880 Inf Inf
[23,] -122.2419  47.76870 Inf Inf
[24,] -122.2722  48.04803 Inf Inf
[25,] -122.2732  47.87700 Inf Inf
[26,] -122.2804  47.77620 Inf Inf
[27,] -122.2839  47.82103 Inf Inf
[28,] -122.2890  47.86899 Inf Inf
[29,] -122.2993  47.67306 Inf Inf
[30,] -122.3180  47.38217 Inf Inf
[31,] -122.3270  47.40378 Inf Inf
[32,] -122.3474  47.43884 Inf Inf
[33,] -122.3484  47.53083 Inf Inf
[34,] -122.3581  47.27678 Inf Inf
[35,] -122.3618  47.76735 Inf Inf
[36,] -122.3700  47.56567 Inf Inf
[37,] -122.3908  47.54938 Inf Inf
[38,] -122.4128  47.64622 Inf Inf
[39,] -122.4293  47.17660 Inf Inf
[40,] -122.4621  47.44505 Inf Inf
[41,] -122.4904  47.27460 Inf Inf
[42,] -122.5515  46.93979 Inf Inf
[43,] -122.7348  42.37320 Inf Inf
[44,] -122.7827  47.31059 Inf Inf
[45,] -122.7987  47.23475 Inf Inf
[46,] -122.8385  42.35119 Inf Inf
[47,] -122.8537  42.34495 Inf Inf
[48,] -122.8904  42.39555 Inf Inf
[49,] -122.8927  42.33022 Inf Inf
[50,] -122.9451  47.37574 Inf Inf
[51,] -122.9594  42.30376 Inf Inf
[52,] -123.0641  47.16428 Inf Inf
[53,] -123.3413  42.44117 Inf Inf
Error in spTransform(xSP, CRSobj, ...) : 
  failure in points 
1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25:26:27:28:29:30:31:32:33:34:35:36:37:38:39:40:41:42:43:44:45:46:47:48:49:50:51:52:53
In addition: Warning message:
In spTransform(xSP, CRSobj, ...) : 53 projected point(s) not finite

Here is the data:
dput(sample)
structure(list(ID = 1:53, Longitude = c(-119.733899, -119.766493, -119.779416, 
-121.0234, -122.004736, -122.013456, -122.0379, -122.0578, -122.132971, 
-122.150901, -122.170608, -122.18462, -122.184639, -122.185079, -122.195398, 
-122.198994, -122.201356, -122.202507, -122.20371, -122.209047, -122.210797, 
-122.229095, -122.2419, -122.27216, -122.273164, -122.280355, -122.28389, 
-122.289043, -122.299261, -122.318009, -122.326987, -122.347382, -122.34844, 
-122.358115, -122.361839, -122.37003, -122.390815, -122.41282, -122.429323, 
-122.462136, -122.490417, -122.551483, -122.734847, -122.782736, -122.798669, 
-122.838498, -122.853683, -122.8904, -122.89271, -122.94511, -122.959407, 
-123.064087, -123.341346), Latitude = c(39.53939, 39.396298, 39.287681, 
39.205028, 47.192616, 47.188833, 47.5219, 47.609748, 47.13669, 47.559616, 
47.155455, 47.234849, 48.15307, 47.448697, 47.684854, 47.516104, 47.447723, 
47.698146, 47.6719, 47.403778, 47.253364, 47.638795, 47.768701, 48.048027, 
47.876997, 47.776205, 

[R-sig-Geo] Help with spTransform() function and final plot colors

2020-05-18 Thread Poling, William via R-sig-Geo
#RStudio Version Version 1.2.1335
sessionInfo()
# R version 4.0.0 Patched (2020-05-03 r78349)
#Platform: x86_64-w64-mingw32/x64 (64-bit) #Running under: Windows 10 x64 
(build 17763)

Hello. I am running my data through a routine I found that finds clusters of 
data points based on distance rule.
https://gis.stackexchange.com/questions/64392/finding-clusters-of-points-based-distance-rule-using-r

1. I get this error when I get to this point in the routine, see complete 
routine below?
xy <- spTransform(xy, CRS("+init=epsg:27700 +datum=WGS84")) non finite 
transformation detected:

I tried converting columns from numeric to Integer but did not help.

However, I continue to run the rest of the routine and the final sequence, the 
plot itself, seems to work Can this error be corrected somehow, despite the 
fact that it continues to work, just curious what it is I guess"

2. However in the plot at the end of the routine the color key appears with the 
colors but the clusters in the plot are black, see plot call at the end of the 
routine below?

Thank you for any advice.

WHP

ERROR:
non finite transformation detected:
  coords.x1 coords.x2
 [1,] -119.7339  39.53939 Inf Inf
 [2,] -119.7665  39.39630 Inf Inf
 [3,] -119.7794  39.28768 Inf Inf
 [4,] -121.0234  39.20503 Inf Inf
 [5,] -122.0047  47.19262 Inf Inf
 [6,] -122.0135  47.18883 Inf Inf
 [7,] -122.0379  47.52190 Inf Inf
 [8,] -122.0578  47.60975 Inf Inf
 [9,] -122.1330  47.13669 Inf Inf
[10,] -122.1509  47.55962 Inf Inf
[11,] -122.1706  47.15546 Inf Inf
[12,] -122.1846  47.23485 Inf Inf
[13,] -122.1846  48.15307 Inf Inf
[14,] -122.1851  47.44870 Inf Inf
[15,] -122.1954  47.68485 Inf Inf
[16,] -122.1990  47.51610 Inf Inf
[17,] -122.2014  47.44772 Inf Inf
[18,] -122.2025  47.69815 Inf Inf
[19,] -122.2037  47.67190 Inf Inf
[20,] -122.2090  47.40378 Inf Inf
[21,] -122.2108  47.25336 Inf Inf
[22,] -122.2291  47.63880 Inf Inf
[23,] -122.2419  47.76870 Inf Inf
[24,] -122.2722  48.04803 Inf Inf
[25,] -122.2732  47.87700 Inf Inf
[26,] -122.2804  47.77620 Inf Inf
[27,] -122.2839  47.82103 Inf Inf
[28,] -122.2890  47.86899 Inf Inf
[29,] -122.2993  47.67306 Inf Inf
[30,] -122.3180  47.38217 Inf Inf
[31,] -122.3270  47.40378 Inf Inf
[32,] -122.3474  47.43884 Inf Inf
[33,] -122.3484  47.53083 Inf Inf
[34,] -122.3581  47.27678 Inf Inf
[35,] -122.3618  47.76735 Inf Inf
[36,] -122.3700  47.56567 Inf Inf
[37,] -122.3908  47.54938 Inf Inf
[38,] -122.4128  47.64622 Inf Inf
[39,] -122.4293  47.17660 Inf Inf
[40,] -122.4621  47.44505 Inf Inf
[41,] -122.4904  47.27460 Inf Inf
[42,] -122.5515  46.93979 Inf Inf
[43,] -122.7348  42.37320 Inf Inf
[44,] -122.7827  47.31059 Inf Inf
[45,] -122.7987  47.23475 Inf Inf
[46,] -122.8385  42.35119 Inf Inf
[47,] -122.8537  42.34495 Inf Inf
[48,] -122.8904  42.39555 Inf Inf
[49,] -122.8927  42.33022 Inf Inf
[50,] -122.9451  47.37574 Inf Inf
[51,] -122.9594  42.30376 Inf Inf
[52,] -123.0641  47.16428 Inf Inf
[53,] -123.3413  42.44117 Inf Inf
Error in spTransform(xSP, CRSobj, ...) : 
  failure in points 
1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25:26:27:28:29:30:31:32:33:34:35:36:37:38:39:40:41:42:43:44:45:46:47:48:49:50:51:52:53
In addition: Warning message:
In spTransform(xSP, CRSobj, ...) : 53 projected point(s) not finite

Here is the data:
dput(sample)
structure(list(ID = 1:53, Longitude = c(-119.733899, -119.766493, -119.779416, 
-121.0234, -122.004736, -122.013456, -122.0379, -122.0578, -122.132971, 
-122.150901, -122.170608, -122.18462, -122.184639, -122.185079, -122.195398, 
-122.198994, -122.201356, -122.202507, -122.20371, -122.209047, -122.210797, 
-122.229095, -122.2419, -122.27216, -122.273164, -122.280355, -122.28389, 
-122.289043, -122.299261, -122.318009, -122.326987, -122.347382, -122.34844, 
-122.358115, -122.361839, -122.37003, -122.390815, -122.41282, -122.429323, 
-122.462136, -122.490417, -122.551483, -122.734847, -122.782736, -122.798669, 
-122.838498, -122.853683, -122.8904, -122.89271, -122.94511, -122.959407, 
-123.064087, -123.341346), Latitude = c(39.53939, 39.396298, 39.287681, 
39.205028, 47.192616, 47.188833, 47.5219, 47.609748, 47.13669, 47.559616, 
47.155455, 47.234849, 48.15307, 47.448697, 47.684854, 47.516104, 47.447723, 
47.698146, 47.6719, 47.403778, 47.253364, 47.638795, 47.768701, 48.048027, 
47.876997, 47.776205, 47.821029, 47.868987, 47.673056, 47.382165, 47.403785, 
47.438836, 47.530831, 47.276776, 47.76735, 47.565667, 47.549377, 47.646222, 
47.176596, 47.445053, 47.274599, 46.939789, 42.373195, 47.310595, 47.234748, 
42.351189, 42.344953, 42.395547, 42.33022, 47.375736, 42.303755, 47.164278, 
42.441172)), class = "data.frame", row.names = c(NA, -53L))

Here is the routine:
require(sp)
require(rgdal)
#25*1609.34 = 40233.5  
dis <- 40233.5 #Distance threshold 25miles converted to meters

x <- tmp1b[,c(6)]
head(x)
y <- tmp1b[,c(5)]
head(y)
str(y)

xy <- SpatialPointsDataFrame(matrix(c(x,y), ncol=2), 
data.frame(ID=seq(1:length(x))),
 

Re: [R-sig-Geo] Help to calculate the impacts using the spreg function in sphet package: GMM/IV with one endogenous and one instrument

2020-05-04 Thread Roger Bivand

On Mon, 4 May 2020, Roger Bivand wrote:


On Sat, 2 May 2020, André M. Marques via R-sig-Geo wrote:


 Dear all,
 I apologize for my previous unclear code in the mail list.Now I hope to be
 clear about the problem I am facing in the following example:

 require("sf", quietly=TRUE)library(sphet)library(spatialreg)
 columbus <- st_read(system.file("shapes/columbus.shp",
 package="spData")[1], quiet=TRUE)require("spdep", quietly=TRUE)col.gal.nb
 <- spdep::read.gal(system.file("weights/columbus.gal",
 package="spData")[1])listw <- spdep::nb2listw(col.gal.nb)
 # I have one endongenous (HOVAL) and one instrument (PLUMB) ## endo=~HOVAL
 ; instruments=~PLUMB

 res.spreg <- spreg(CRIME ~ INC + OPEN, columbus,
 listw,endo=~HOVAL,lag.instr =
 TRUE,instruments=~PLUMB,model=c('ivhac'),het=TRUE,HAC=FALSE)
 class(res.spreg)#[1] "sphet"  "gstsls"summary(res.spreg)
 Now the problem: I'm unable to calculate the impacts and their p-values in
 a (cross-section) Cliff-Ord model based on GMM/IV:



Had you followed list rules and posted plain text, things might have been 
clearer. HTML tries to make code look like a paragraph of text, so messes 
everything up. This is a plain-text version:


library(sphet)
library(spatialreg)
columbus <- sf::st_read(system.file("shapes/columbus.shp",
 package="spData")[1], quiet=TRUE)
col.gal.nb <- spdep::read.gal(system.file("weights/columbus.gal",
 package="spData")[1])
listw <- spdep::nb2listw(col.gal.nb)
res.spreg <- spreg(CRIME ~ INC + OPEN, columbus, listw, endo=~HOVAL,
  lag.instr = TRUE, instruments=~PLUMB, model=c('ivhac'), het=TRUE,
  HAC=FALSE)
class(res.spreg)
summary(res.spreg)
impacts(res.spreg, listw=listw)

This indicates a mismatch firstly between released spatialreg and spdep in 
handling impacts for some sphet objects, and further that the IV case may not 
yet be covered. Please provide this reproducible example on 
https://github.com/r-spatial/spatialreg/issues and ping the sphet maintainer.


There was a mismatch in declaration of method imports. Try:

install.packages("sphet", repos="http://R-Forge.R-project.org;)
remotes::install_github("r-spatial/spatialreg")

if it posssible for you to install packages from source; the example was 
helpful in making progress. If you can install the fresh package versions, 
please also report whether the underlying  problem is resolved on your 
real data.


Roger



Roger



 W <- as(listw, "CsparseMatrix")trMatc <- trW(W, type="mult")trMC <- trW(W,
 type="MC")
 set.seed(1234)impacts(res.spreg, listw=listw)
#  I get the error message:Error in spatialreg::intImpacts(rho = rho, beta 
#  = beta, P = P, n = n,  :   argumento "evalues" ausente, sem padrãoAlém 
#  disso: Warning message:Function intImpacts moved to the spatialreg 
#  package
#  or even when I try:library(coda)lobjIQ5 <- impacts(res.spreg, tr=trMatc, 
#  R=200, Q=5)summary(lobjIQ5, zstats=TRUE, short=TRUE)# I got the same 
#  error message.

 ## When I use the 'evalues' argument as the vector of eigenvalues of
 spatial weights matrix:
 ev <- eigenw(listw)impacts(res.spreg, evalues=ev)
 # Even in this way I got the same error message.

 Thanks for help.
 Best wishes,
 André M. Marques
 Federal University of ParaibaGraduate Program of Economics


  [[alternative HTML version deleted]]

 ___
 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
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


Re: [R-sig-Geo] Help to calculate the impacts using the spreg function in sphet package: GMM/IV with one endogenous and one instrument

2020-05-04 Thread Roger Bivand

On Sat, 2 May 2020, André M. Marques via R-sig-Geo wrote:


Dear all,
I apologize for my previous unclear code in the mail list.Now I hope to be 
clear about the problem I am facing in the following example:

require("sf", quietly=TRUE)library(sphet)library(spatialreg)
columbus <- st_read(system.file("shapes/columbus.shp", package="spData")[1], quiet=TRUE)require("spdep", 
quietly=TRUE)col.gal.nb <- spdep::read.gal(system.file("weights/columbus.gal", package="spData")[1])listw <- 
spdep::nb2listw(col.gal.nb)
# I have one endongenous (HOVAL) and one instrument (PLUMB) ## endo=~HOVAL ; 
instruments=~PLUMB

res.spreg <- spreg(CRIME ~ INC + OPEN, columbus, listw,endo=~HOVAL,lag.instr = 
TRUE,instruments=~PLUMB,model=c('ivhac'),het=TRUE,HAC=FALSE)
class(res.spreg)#[1] "sphet"  "gstsls"summary(res.spreg)
Now the problem: I'm unable to calculate the impacts and their p-values in a 
(cross-section) Cliff-Ord model based on GMM/IV:



Had you followed list rules and posted plain text, things might have been 
clearer. HTML tries to make code look like a paragraph of text, so messes 
everything up. This is a plain-text version:


library(sphet)
library(spatialreg)
columbus <- sf::st_read(system.file("shapes/columbus.shp",
  package="spData")[1], quiet=TRUE)
col.gal.nb <- spdep::read.gal(system.file("weights/columbus.gal",
  package="spData")[1])
listw <- spdep::nb2listw(col.gal.nb)
res.spreg <- spreg(CRIME ~ INC + OPEN, columbus, listw, endo=~HOVAL,
  lag.instr = TRUE, instruments=~PLUMB, model=c('ivhac'), het=TRUE,
  HAC=FALSE)
class(res.spreg)
summary(res.spreg)
impacts(res.spreg, listw=listw)

This indicates a mismatch firstly between released spatialreg and spdep in 
handling impacts for some sphet objects, and further that the IV case may 
not yet be covered. Please provide this reproducible example on 
https://github.com/r-spatial/spatialreg/issues and ping the sphet 
maintainer.


Roger



W <- as(listw, "CsparseMatrix")trMatc <- trW(W, type="mult")trMC <- trW(W, 
type="MC")
set.seed(1234)impacts(res.spreg, listw=listw)
# I get the error message:Error in spatialreg::intImpacts(rho = rho, beta = beta, P = P, 
n = n,  :   argumento "evalues" ausente, sem padrãoAlém disso: Warning 
message:Function intImpacts moved to the spatialreg package
# or even when I try:library(coda)lobjIQ5 <- impacts(res.spreg, tr=trMatc, 
R=200, Q=5)summary(lobjIQ5, zstats=TRUE, short=TRUE)# I got the same error message.
## When I use the 'evalues' argument as the vector of eigenvalues of spatial 
weights matrix:
ev <- eigenw(listw)impacts(res.spreg, evalues=ev)
# Even in this way I got the same error message.

Thanks for help.
Best wishes,
André M. Marques
Federal University of ParaibaGraduate Program of Economics


[[alternative HTML version deleted]]

___
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
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


[R-sig-Geo] Help to calculate the impacts using the spreg function in sphet package: GMM/IV with one endogenous and one instrument

2020-05-02 Thread André M . Marques via R-sig-Geo
Dear all,
I apologize for my previous unclear code in the mail list.Now I hope to be 
clear about the problem I am facing in the following example:

require("sf", quietly=TRUE)library(sphet)library(spatialreg)
columbus <- st_read(system.file("shapes/columbus.shp", package="spData")[1], 
quiet=TRUE)require("spdep", quietly=TRUE)col.gal.nb <- 
spdep::read.gal(system.file("weights/columbus.gal", package="spData")[1])listw 
<- spdep::nb2listw(col.gal.nb)
# I have one endongenous (HOVAL) and one instrument (PLUMB) ## endo=~HOVAL ; 
instruments=~PLUMB

res.spreg <- spreg(CRIME ~ INC + OPEN, columbus, listw,endo=~HOVAL,lag.instr = 
TRUE,instruments=~PLUMB,model=c('ivhac'),het=TRUE,HAC=FALSE)
class(res.spreg)#[1] "sphet"  "gstsls"summary(res.spreg)
Now the problem: I'm unable to calculate the impacts and their p-values in a 
(cross-section) Cliff-Ord model based on GMM/IV:

W <- as(listw, "CsparseMatrix")trMatc <- trW(W, type="mult")trMC <- trW(W, 
type="MC")
set.seed(1234)impacts(res.spreg, listw=listw)
# I get the error message:Error in spatialreg::intImpacts(rho = rho, beta = 
beta, P = P, n = n,  :   argumento "evalues" ausente, sem padrãoAlém disso: 
Warning message:Function intImpacts moved to the spatialreg package
# or even when I try:library(coda)lobjIQ5 <- impacts(res.spreg, tr=trMatc, 
R=200, Q=5)summary(lobjIQ5, zstats=TRUE, short=TRUE)# I got the same error 
message.
## When I use the 'evalues' argument as the vector of eigenvalues of spatial 
weights matrix:
ev <- eigenw(listw)impacts(res.spreg, evalues=ev)
# Even in this way I got the same error message.

Thanks for help.
Best wishes,
André M. Marques
Federal University of ParaibaGraduate Program of Economics


[[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] Help to calculate the impacts using the spreg function in sphet package: GMM/IV with one endogenous and one instrument

2020-05-02 Thread André M . Marques via R-sig-Geo
Dear all,
# I am facing the following problem in calculating the impacts and their 
significance based on 'impacts' function in# {spatialreg} package:# I have one 
endogenous (HOVAL) and one instrument (PLUMB) ## endo=~HOVAL ; 
instruments=~PLUMB
# How can I calculate the impact measures and their significance based on 
GMM/IV of 'spreg ( )' function in sphet package# when I have one endogenous and 
one instrument?
# My reproducible example:require("sf", 
quietly=TRUE)library(sphet)library(spatialreg)
columbus <- st_read(system.file("shapes/columbus.shp", package="spData")[1], 
quiet=TRUE)require("spdep", quietly=TRUE)col.gal.nb <- 
spdep::read.gal(system.file("weights/columbus.gal", package="spData")[1])listw 
<- spdep::nb2listw(col.gal.nb)
# I have one endongenous (HOVAL) and one instrument (PLUMB) ## endo=~HOVAL ; 
instruments=~PLUMB # res.spreg <- spreg(CRIME ~ INC + OPEN, columbus, listw,    
               endo=~HOVAL,lag.instr = TRUE,instruments=~PLUMB,                 
  model=c('ivhac'),het=TRUE,HAC=FALSE)class(res.spreg)#[1] "sphet"  
"gstsls"summary(res.spreg)
#
 Now the problem: I'm unable to calculate the impacts in a (cross-section) 
Cliff-Ord model based on GMM/IV 
#
W <- as(listw, "CsparseMatrix")trMatc <- trW(W, type="mult")trMC <- trW(W, 
type="MC")
set.seed(1234)impacts(res.spreg, listw=listw)
# I get the error message:Error in spatialreg::intImpacts(rho = rho, beta = 
beta, P = P, n = n,  :   argumento "evalues" ausente, sem padrãoAlém disso: 
Warning message:Function intImpacts moved to the spatialreg package 

# or even:library(coda)lobjIQ5 <- impacts(res.spreg, tr=trMatc, R=200, 
Q=5)summary(lobjIQ5, zstats=TRUE, short=TRUE)
# When I use the 'evalues' argument as the vector of eigenvalues of spatial 
weights matrix:
ev <- eigenw(listw)impacts(res.spreg, evalues=ev)
# I get the error:
Error in spatialreg::intImpacts(rho = rho, beta = beta, P = P, n = n,  :   
argumento "evalues" ausente, sem padrão


Thanks for some help,
Best wishes,

André M. MarquesFederal University of Paraiba
Department of EconomicsGraduate Program of Economics



[[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: assign crs to RasterBrick

2020-04-29 Thread Michael Sumner
You need to also setExtent() of the raster. That's the coordinates that the
crs refers to xmin,xmax,ymin,ymax values in metres. Sometimes visual cues
can be used to derive these from an image, sometimes the grid is a commonly
used convention (a certain dimension, I.e. extent +resolution in a region).
It really needs the file source itself or some info from the provider where
the data was already a map.

Not much can be done from a picture alone though.

I'll have a look around sometimes wild guesses work because projection-use
is rarely bespoke.

Best




On Mon., 27 Apr. 2020, 01:21 Jesús Rojo,  wrote:

> Hello everyone
> I have a flipped RasterBrick without crs assigned (crs = NA):
> plot(a[[100]]
> I would like to fill the map and assign the correct coordinate systems,
> that it has been said to me to be specifically:
>
> "+init=EPSG:3034 +proj=lcc +lat_1=35 +lat_2=65 +lat_0=50 +lon_0=10
> +x_0=400 +y_0=280 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m
> +no_defs”
>
> I try to solve with the next commands for the raster library:
>
> In a first step I have flipped the map, and it has been right with:
>
> a <- t(flip(a, direction='y' ))
>
> But I have problems with the assignments of the suitable crs.
>
> crs(a) <- "+init=EPSG:3034 +proj=lcc +lat_1=35 +lat_2=65 +lat_0=50
> +lon_0=10 +x_0=400 +y_0=280 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0
> +units=m +no_defs”
>
> Because although the map assigns crs = “+init = EPSG:3034”, the map
> doesn’t seem georreferenced, because the starting point of the map is
> (0,0). My final objective is  to transform the crs to "+proj=longlat
> +datum=WGS84”
>
> A <- projectRaster(a, crs = "+proj=longlat +datum=WGS84")
> I will be grateful some kind of help. Do I need more additional
> information? Any step is wrong?
> Thank you so much
> Jesús Rojo
> ___
> 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] Help: assign crs to RasterBrick

2020-04-29 Thread Jesús Rojo


> Hello everyone
> I have a flipped RasterBrick without crs assigned (crs = NA):
> plot(a[[100]]
> 
> I would like to fill the map and assign the correct coordinate systems, that 
> it has been said to me to be specifically:
> 
> "+init=EPSG:3034 +proj=lcc +lat_1=35 +lat_2=65 +lat_0=50 +lon_0=10 
> +x_0=400 +y_0=280 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m 
> +no_defs”
> 
> I try to solve with the next commands for the raster library:
> 
> In a first step I have flipped the map, and it has been right with:
> 
> a <- t(flip(a, direction='y' ))
> 
> But I have problems with the assignments of the suitable crs.
> 
> crs(a) <- "+init=EPSG:3034 +proj=lcc +lat_1=35 +lat_2=65 +lat_0=50 +lon_0=10 
> +x_0=400 +y_0=280 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m 
> +no_defs”
> 
> Because although the map assigns crs = “+init = EPSG:3034”, the map doesn’t 
> seem georreferenced, because the starting point of the map is (0,0). My final 
> objective is  to transform the crs to "+proj=longlat +datum=WGS84”
> 
> A <- projectRaster(a, crs = "+proj=longlat +datum=WGS84")
> 
> I will be grateful some kind of help. Do I need more additional information? 
> Any step is wrong?
> Thank you so much
> Jesús Rojo

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


[R-sig-Geo] Help: assign crs to RasterBrick

2020-04-26 Thread Jesús Rojo
Hello everyone
I have a flipped RasterBrick without crs assigned (crs = NA):
plot(a[[100]]

I would like to fill the map and assign the correct coordinate systems, that it 
has been said to me to be specifically:

"+init=EPSG:3034 +proj=lcc +lat_1=35 +lat_2=65 +lat_0=50 +lon_0=10 +x_0=400 
+y_0=280 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs”

I try to solve with the next commands for the raster library:

In a first step I have flipped the map, and it has been right with:

a <- t(flip(a, direction='y' ))

But I have problems with the assignments of the suitable crs.

crs(a) <- "+init=EPSG:3034 +proj=lcc +lat_1=35 +lat_2=65 +lat_0=50 +lon_0=10 
+x_0=400 +y_0=280 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs”

Because although the map assigns crs = “+init = EPSG:3034”, the map doesn’t 
seem georreferenced, because the starting point of the map is (0,0). My final 
objective is  to transform the crs to "+proj=longlat +datum=WGS84”

A <- projectRaster(a, crs = "+proj=longlat +datum=WGS84")

I will be grateful some kind of help. Do I need more additional information? 
Any step is wrong?
Thank you so much
Jesús Rojo___
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-13 Thread Bakary Faty
Dear Silver,

Thank for your help.

I think there had been a mix-up in the Coordinate Rference System. When I
plot this shapefile I get
it in the UTM Coordinate.
Le Senegal is in Zone 28 North. The watershed on what I work is shared by
trois Countries (Senegal, Gambie and Guinea).
But in the choose of UTM 33 in my script is an error.
Thank very much.

Best regards


Le lun. 13 janv. 2020 à 07:22, Micha Silver  a écrit :

> Hello Bakary:
>
> Please keep questions on the list, so that others can benefit from the
> conversation.
>
>
> I see that the Basins shapefile you sent is declared to be in Long/Lat
> WGS84 Coordinate Reference System, however the coordinates (the X-Y
> locations) look like it is already projected to UTM 33. Is it possible
> there is some mixup in the Coordinate Reference System of the Basins
> shapefile?
>
> (That would explain why the basins layer does not appear on your plot)
>
>
> Furthermore, I think that you are working in Senegal/Gambia (from the
> coordinates in the DATAFILE). If so, why did you choose to project to UTM
> 33 in your script? Isn't Senegal in UTM zone 28?
>
>
> Attached is the corrected script (changed to UTM28). The corrected basin
> shapefile is sent privately. (too big for the list)
>
>
> Regards, Micha
>
>
>
>
> On 12/01/2020 21:29, Bakary Faty wrote:
>
> Dear Micha Silver
>
> I'm writing you this email following your contribution on my isohyet map
> code, in 'r-sig-geo'.
>
> I really appreciated your help which helped me a lot. I can draw the
> isohyets but I can't draw the contour of my study basin.
>
> You can see where the problem is in the code to make a change again?
>
> You will find the files of the watershed and my code R attached.
>
> Thank you very much by advance
>
>
> Best regards
>
> Le ven. 10 janv. 2020 à 09:41, Micha Silver  a écrit :
>
>>
>> On 09/01/2020 21:02, 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 and my data file.
>> > Best regards
>> >
>>
>>
>> I made two small changes in your code, and it works fine:
>>
>>   * First I used the suggestion (earlier in this thread) to create your
>> grid.
>>   * Then, you had an error in your call to autoKrige.
>>   * After getting that right, I created isohyetal lines with
>> rasterToContour
>>
>> Here's my version
>>
>>
>> library(automap)
>> library(raster)
>> library(rgdal)
>>
>> ## READ INPUT FILE
>> rain_data <- read.csv(file="DATAFILE_FOR_ISOHYET.csv")
>>
>> point_coords <- rain_data[c("Lon","Lat")]
>> coordinates(rain_data) <- point_coords
>> p4str <- CRS("+init=epsg:4326")
>> proj4string(rain_data) <- p4str
>>
>> ## CONVERTION TO UTM
>> p4str_UTM <- CRS("+init=epsg:32633")
>> rain_data_UTM <- spTransform(rain_data, p4str_UTM)
>>
>>
>> bb <- bbox(rain_data_UTM)
>> minx <- bb[1,1]
>> maxx <- bb[1,2]
>> miny <- bb[2,1]
>> maxy <- bb[2,2]
>>
>> ## EACH PIXEL WILL BE 1000 METERS
>> pixel <- 1000
>> grd <- expand.grid(x=seq(minx, maxx, by=pixel), y=seq(miny, maxy,
>> by=pixel))
>> coordinates(grd) <- ~x+y
>> gridded(grd) <- TRUE
>> proj4string(grd) <- p4str_UTM
>>
>>
>> ## KRIGING, USING AUTOKRIGE WHICH CREATES A BEST GUESS VARIOGRAM
>> # OK_rain <- autoKrige(Rainfall_value ~ 1, rain_data_UTM, grd)
>> # There is no variable "Rainfall_value" in your data,
>> # It is called RAIN_DATA
>> OK_rain = autoKrige(formula = RAIN_DATA ~1,
>>  input_data = rain_data_UTM,
>>  new_data = grd)
>>
>> ## TRASFORM TO RASTER
>> rain_rast <- raster(OK_rain$krige_output)
>>
>> summary(rain_rast)
>>
>>
>> # Minimumn is 540, max is 1735
>> # So create isohyetal lines about every 100 mm and plot
>>
>> isohyets = rasterToContour(rain_rast, nlevels = 12)
>> plot(rain_rast)
>> lines(isohyets, add = TRUE)
>>
>>
>> > Le jeu. 9 janv. 2020 à 18:41, Bakary Faty > > > a écrit :
>> >
>> > 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?
>> >

Re: [R-sig-Geo] Help

2020-01-12 Thread Micha Silver

  
  
Hello Bakary:
Please keep questions on the list, so that others can benefit
  from the conversation.


I see that the Basins shapefile you sent is declared to be in
  Long/Lat WGS84 Coordinate Reference System, however the
  coordinates (the X-Y locations) look like it is already projected
  to UTM 33. Is it possible there is some mixup in the Coordinate
  Reference System of the Basins shapefile?
(That would explain why the basins layer does not appear on your
  plot)


Furthermore, I think that you are working in Senegal/Gambia (from
  the coordinates in the DATAFILE). If so, why did you choose to
  project to UTM 33 in your script? Isn't Senegal in UTM zone 28?


Attached is the corrected script (changed to UTM28). The
  corrected basin shapefile is sent privately. (too big for the
  list)



Regards, Micha






On 12/01/2020 21:29, Bakary Faty wrote:


  
  

  Dear Micha Silver
  I'm writing you this email following your
  contribution
  on my isohyet map code, in 'r-sig-geo'.
  I really appreciated your help which helped
  me a lot.
  I can draw the isohyets but I can't draw the contour of my
  study basin. 
  You can see where the problem is in the code
  to make a change again?
  You will find the files of the
  watershed and my code R attached.
  Thank you very much by
  advance
  
  

  Best regards

  
  
  
Le ven. 10 janv. 2020 à 09:41,
  Micha Silver  a écrit :


  On 09/01/2020 21:02, 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 and my data file.
  > Best regards
  >
  
  
  I made two small changes in your code, and it works fine:
  
    * First I used the suggestion (earlier in this thread) to
  create your
      grid.
    * Then, you had an error in your call to autoKrige.
    * After getting that right, I created isohyetal lines with 
  rasterToContour
  
  Here's my version
  
  
  library(automap)
  library(raster)
  library(rgdal)
  
  ## READ INPUT FILE
  rain_data <- read.csv(file="DATAFILE_FOR_ISOHYET.csv")
  
  point_coords <- rain_data[c("Lon","Lat")]
  coordinates(rain_data) <- point_coords
  p4str <- CRS("+init=epsg:4326")
  proj4string(rain_data) <- p4str
  
  ## CONVERTION TO UTM
  p4str_UTM <- CRS("+init=epsg:32633")
  rain_data_UTM <- spTransform(rain_data, p4str_UTM)
  
  
  bb <- bbox(rain_data_UTM)
  minx <- bb[1,1]
  maxx <- bb[1,2]
  miny <- bb[2,1]
  maxy <- bb[2,2]
  
  ## EACH PIXEL WILL BE 1000 METERS
  pixel <- 1000
  grd <- expand.grid(x=seq(minx, maxx, by=pixel), y=seq(miny,
  maxy, 
  by=pixel))
  coordinates(grd) <- ~x+y
  gridded(grd) <- TRUE
  proj4string(grd) <- p4str_UTM
  
  
  ## KRIGING, USING AUTOKRIGE WHICH CREATES A BEST GUESS
  VARIOGRAM
  # OK_rain <- autoKrige(Rainfall_value ~ 1, rain_data_UTM,
  grd)
  # There is no variable "Rainfall_value" in your data,
  # It is called RAIN_DATA
  OK_rain = autoKrige(formula = RAIN_DATA ~1,
   input_data = rain_data_UTM,
   new_data = grd)
  
  ## TRASFORM TO RASTER
  rain_rast <- raster(OK_rain$krige_output)
  
  summary(rain_rast)
  
  
  # Minimumn is 540, max is 1735
  # So create isohyetal lines about every 100 mm and plot
  
  isohyets = rasterToContour(rain_rast, nlevels = 12)
  plot(rain_rast)
  lines(isohyets, add = TRUE)
  
  
  > Le jeu. 9 janv. 2020 à 18:41, Bakary Faty  bakaryf...@gmail.com>>
  a écrit :
  >
  >     Thank you for appreciated reply,
  >
  >     I explane you exactly what I want to do with this R
  code attached.
  >     I want 

Re: [R-sig-Geo] Help

2020-01-10 Thread Bakary Faty
Thank you very much for help,
The code works fine but when I add the shapefile of my watershed
I can not plot it.

Le ven. 10 janv. 2020 à 09:41, Micha Silver  a écrit :

>
> On 09/01/2020 21:02, 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 and my data file.
> > Best regards
> >
>
>
> I made two small changes in your code, and it works fine:
>
>   * First I used the suggestion (earlier in this thread) to create your
> grid.
>   * Then, you had an error in your call to autoKrige.
>   * After getting that right, I created isohyetal lines with
> rasterToContour
>
> Here's my version
>
>
> library(automap)
> library(raster)
> library(rgdal)
>
> ## READ INPUT FILE
> rain_data <- read.csv(file="DATAFILE_FOR_ISOHYET.csv")
>
> point_coords <- rain_data[c("Lon","Lat")]
> coordinates(rain_data) <- point_coords
> p4str <- CRS("+init=epsg:4326")
> proj4string(rain_data) <- p4str
>
> ## CONVERTION TO UTM
> p4str_UTM <- CRS("+init=epsg:32633")
> rain_data_UTM <- spTransform(rain_data, p4str_UTM)
>
>
> bb <- bbox(rain_data_UTM)
> minx <- bb[1,1]
> maxx <- bb[1,2]
> miny <- bb[2,1]
> maxy <- bb[2,2]
>
> ## EACH PIXEL WILL BE 1000 METERS
> pixel <- 1000
> grd <- expand.grid(x=seq(minx, maxx, by=pixel), y=seq(miny, maxy,
> by=pixel))
> coordinates(grd) <- ~x+y
> gridded(grd) <- TRUE
> proj4string(grd) <- p4str_UTM
>
>
> ## KRIGING, USING AUTOKRIGE WHICH CREATES A BEST GUESS VARIOGRAM
> # OK_rain <- autoKrige(Rainfall_value ~ 1, rain_data_UTM, grd)
> # There is no variable "Rainfall_value" in your data,
> # It is called RAIN_DATA
> OK_rain = autoKrige(formula = RAIN_DATA ~1,
>  input_data = rain_data_UTM,
>  new_data = grd)
>
> ## TRASFORM TO RASTER
> rain_rast <- raster(OK_rain$krige_output)
>
> summary(rain_rast)
>
>
> # Minimumn is 540, max is 1735
> # So create isohyetal lines about every 100 mm and plot
>
> isohyets = rasterToContour(rain_rast, nlevels = 12)
> plot(rain_rast)
> lines(isohyets, add = TRUE)
>
>
> > Le jeu. 9 janv. 2020 à 18:41, Bakary Faty  > > a écrit :
> >
> > 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
> > mailto:bakaryf...@gmail.com>> 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 
> >

Re: [R-sig-Geo] Help

2020-01-10 Thread Micha Silver



On 09/01/2020 21:02, 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 and my data file.
Best regards




I made two small changes in your code, and it works fine:

 * First I used the suggestion (earlier in this thread) to create your
   grid.
 * Then, you had an error in your call to autoKrige.
 * After getting that right, I created isohyetal lines with 
rasterToContour


Here's my version


library(automap)
library(raster)
library(rgdal)

## READ INPUT FILE
rain_data <- read.csv(file="DATAFILE_FOR_ISOHYET.csv")

point_coords <- rain_data[c("Lon","Lat")]
coordinates(rain_data) <- point_coords
p4str <- CRS("+init=epsg:4326")
proj4string(rain_data) <- p4str

## CONVERTION TO UTM
p4str_UTM <- CRS("+init=epsg:32633")
rain_data_UTM <- spTransform(rain_data, p4str_UTM)


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

## EACH PIXEL WILL BE 1000 METERS
pixel <- 1000
grd <- expand.grid(x=seq(minx, maxx, by=pixel), y=seq(miny, maxy, 
by=pixel))

coordinates(grd) <- ~x+y
gridded(grd) <- TRUE
proj4string(grd) <- p4str_UTM


## KRIGING, USING AUTOKRIGE WHICH CREATES A BEST GUESS VARIOGRAM
# OK_rain <- autoKrige(Rainfall_value ~ 1, rain_data_UTM, grd)
# There is no variable "Rainfall_value" in your data,
# It is called RAIN_DATA
OK_rain = autoKrige(formula = RAIN_DATA ~1,
    input_data = rain_data_UTM,
    new_data = grd)

## TRASFORM TO RASTER
rain_rast <- raster(OK_rain$krige_output)

summary(rain_rast)


# Minimumn is 540, max is 1735
# So create isohyetal lines about every 100 mm and plot

isohyets = rasterToContour(rain_rast, nlevels = 12)
plot(rain_rast)
lines(isohyets, add = TRUE)


Le jeu. 9 janv. 2020 à 18:41, Bakary Faty > a écrit :


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 mailto:btup...@bigelow.org>> 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
mailto:bakaryf...@gmail.com>> 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



--



Bakary

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


--
Micha Silver
Ben Gurion Univ.
Sde Boker, Remote Sensing Lab
cell: +972-523-665918
https://orcid.org/-0002-1128-1325

___

Re: [R-sig-Geo] Help

2020-01-09 Thread Bakary Faty
Thanks very much angain,
 I'll check them out.

Best regards

Le jeu. 9 janv. 2020 à 19:05, Ben Tupper  a écrit :

> 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
>
>

-- 



Bakary

[[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
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 Bakary Faty
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 and my data file.
Best regards

Le jeu. 9 janv. 2020 à 18:41, Bakary Faty  a écrit :

> 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
>


-- 



Bakary


DATAFILE_FOR_ISOHYET.csv
Description: MS-Excel spreadsheet


R_code_for_rainfall_isohyet_map.R
Description: Binary data
___
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


[R-sig-Geo] Help

2020-01-09 Thread Bakary Faty
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


pointfile.csv
Description: MS-Excel spreadsheet
___
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 with simple Map of US states to predefined regions

2018-09-14 Thread Bill Poling
Thank you Jerome, I will peruse and let you know.

Best regards
WHP


From: Jérome Mathieu 
Sent: Friday, September 14, 2018 3:37 AM
To: Bill Poling 
Cc: r-sig-geo 
Subject: Re: [R-sig-Geo] Help with simple Map of US states to predefined regions

Hi,

this might help you:

http://socviz.co/maps.html#maps<http://socviz.co/maps.html#maps>
http://strimas.com/r/tidy-sf/<http://strimas.com/r/tidy-sf/>
https://cran.r-project.org/web/packages/fiftystater/vignettes/fiftystater.html<https://cran.r-project.org/web/packages/fiftystater/vignettes/fiftystater.html>

Jerome





Le mer. 12 sept. 2018 à 20:27, Bill Poling 
mailto:bill.pol...@zelis.com>> a écrit :
>
> Hi
>
> I have this df with three columns ProviderState, ProviderStateCode, 
> ProviderRegion I wanted to use to create a simple 5 color map
>
> I have reviewed fiftystater pkg and map pkg but not sure how to simply take 
> these three columns and plot a simple 5 color map based on the Region the 
> state is in?
>
> After looking at these and trying to apply these ideas to my data
> https://cran.r-project.org/web/packages/fiftystater/vignettes/fiftystater.html<https://cran.r-project.org/web/packages/fiftystater/vignettes/fiftystater.html>
> https://cran.r-project.org/web/packages/maps/maps.pdf<https://cran.r-project.org/web/packages/maps/maps.pdf>
>
> I found tutorial at: 
> https://uchicagoconsulting.wordpress.com/tag/r-ggplot2-maps-visualization/<https://uchicagoconsulting.wordpress.com/tag/r-ggplot2-maps-visualization/>
>
> I used the tutorial data and subset in my regions
>
> So now I have come up with the 5 segmented maps and my question becomes how 
> to put this all into one map of the US?
>
>
> install.packages("maps")
> library(maps)
> library(ggplot2)
>
> #load us map data
> all_states <- map_data("state") View(all_states)
> #plot all states with ggplot
> p <- ggplot()
> p <- p + geom_polygon( data=all_states, aes(x=long, y=lat, group = 
> group),colour="white", fill="blue" )
> p
>
> #http://sape.inf.usi.ch/quick-reference/ggplot2/colour<http://sape.inf.usi.ch/quick-reference/ggplot2/colour>
>
> #Pacificstates
> Pacificstates <- subset(all_states, region %in% c( "alaska", "arizona", 
> "california", "hawaii", "nevada", "oregon","washington") )
> p <- ggplot()
> p <- p + geom_polygon( data=Pacificstates, aes(x=long, y=lat, group = 
> group),colour="white", fill="deepskyblue4" ) +
>   labs(title = "Pacificstates")
> p
>
> #Frontierstates
> Frontierstates <- subset(all_states, region %in% c( "colorado", "idaho", 
> "kansas", "montana", "new mexico", "oklahoma","texas", "utah", "wyoming") )
> p <- ggplot()
> p <- p + geom_polygon( data=Frontierstates, aes(x=long, y=lat, group = 
> group),colour="white", fill="dodgerblue1" ) +
>   labs(title = "FrontierStates")
> p
>
> #Midweststates
> Midweststates <- subset(all_states, region %in% c( "iowa", "illinois", 
> "indiana", "michigan", "minnesota", "missouri","north dakota", "nebraska", 
> "ohio","south dakota","wisconsin") )
> p <- ggplot()
> p <- p + geom_polygon( data=Midweststates, aes(x=long, y=lat, group = 
> group),colour="white", fill="dodgerblue1" ) +
>   labs(title = "MidwestStates")
> p
>
> #Southernstates
> Southernstates <- subset(all_states, region %in% c( "alabama", "arkansas", 
> "florida", "georgia", "kentucky", "louisiana","mississippi"
> ,"north carolina", "south 
> carolina","tennessee","virginia","west virginia") )
> p <- ggplot()
> p <- p + geom_polygon( data=Southernstates, aes(x=long, y=lat, group = 
> group),colour="white", fill="royalblue2" ) +
>   labs(title = "Southernstates")
> p
>
> # Northeaststates
> Northeaststates <- subset(all_states, region %in% c( "connecticut", "district 
> of columbia", "delaware", "massachusetts", "maryland", "maine","new hampshire"
>  , "new jersey", "new 
> york","pennsylvania","rhode island","vermont") )
> p <- ggplot()
> p <

[R-sig-Geo] Help with simple Map of US states with predefined regions Version 2 (Solved)

2018-09-14 Thread Bill Poling
Good morning Don, I cannot thank you enough for your support and the trouble 
you went to.
I am novice useR and the only analyst in the shop asked to learn R and the 
demands are growing faster than my knowledge intake, lots of laughs!

Best regards

WHP

From: MacQueen, Don 
Sent: Thursday, September 13, 2018 4:41 PM
To: Bill Poling ; r-sig-geo@r-project.org
Subject: Re: [R-sig-Geo] Help with simple Map of US states with predefined 
regions Version 2

I know this is not a complete solution -- and it's a very different approach -- 
but it should at least show you a way to reliably get states colored by region.
(I also left out Alaska and Hawaii, since the point here is how to color the 
regions)

require(sp)
require(rgdal)

## US Census Bureau Tiger file -- polygons of each US State
## try this URL for download
## 
https://www.census.gov/cgi-bin/geo/shapefiles/index.php?year=2017=States+%28and+equivalent%29<https://www.census.gov/cgi-bin/geo/shapefiles/index.php?year=2017=States+%28and+equivalent%29>

## unzip to working directory ( '.' )
ustf <- readOGR('.', 'tl_2017_us_state', stringsAsFactors=FALSE)

## note, the Tiger file includes 6 additional territories
dim(ustf)
## [1] 56 14

## get rid of the extra six territories (state.name<http://state.name> comes 
with R)
cus <- subset(ustf, NAME %in% state.name<http://state.name>)

## cheap rename
cus$state <- cus$NAME
cus$abb <- cus$STUSPS

## invent ridiculous groupings of states
cus$grp <- 'a'
cus$grp[11:20] <- 'b'
cus$grp[21:30] <- 'c'
cus$grp[31:40] <- 'd'
cus$grp[41:50] <- 'e'

## assign colors to the groups
cus$color <- 'red'
cus$color[cus$grp=='b'] <- 'green'
cus$color[cus$grp=='c'] <- 'blue'
cus$color[cus$grp=='d'] <- 'brown'
cus$color[cus$grp=='e'] <- 'cyan'

## exclude Alaska, Hawaii
cus <- subset(cus, !(state %in% c('Alaska','Hawaii')))

## get rid of extraneous variables (optional)
cus <- cus[ , c('state','REGION','abb', 'grp') ]

## plot colored by regions as defined in the Census Bureau Tiger file
plot(cus, col=cus$REGION, usePolypath=FALSE)

## color "1" is black, looks bad, do this instead
plot(cus, col=as.numeric(cus$REGION)+1, usePolypath=FALSE)
text(coordinates(cus), cus$abb, col='white', cex=0.75)

## colors specified by a color variable in the data
plot(cus, col=cus$color, usePolypath=FALSE)
text(coordinates(cus), cus$abb, col='white', cex=0.75)

(my preferred graphics device does not support Polypath, but probably most 
others do, so one can omit usePolypath=FALSE)

-Don

--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
Lab cell 925-724-7509



On 9/13/18, 5:17 AM, "R-sig-Geo on behalf of Bill Poling" 
mailto:r-sig-geo-boun...@r-project.org%20on%20behalf%20of%20bill.pol...@zelis.com>>
 wrote:

Hi,

I hope someone can help me finalize this please.

I am coming close to what I need using variations from two ggplot2 tutorials.

This first gives me the map of the US with AK & HI but I cannot figure out how 
to get my 5 regions colored

#https://stackoverflow.com/questions/38021188/how-to-draw-u-s-state-map-with-hi-and-ak-with-state-abbreviations-centered-us?rq=1<https://stackoverflow.com/questions/38021188/how-to-draw-u-s-state-map-with-hi-and-ak-with-state-abbreviations-centered-us?rq=1>


library(ggplot2)
install.packages("ggalt")
library(ggalt) # coord_proj
library(albersusa) # devtools::install_github("hrbrmstr/albersusa")
install.packages("ggthemes")
library(ggthemes) # theme_map
install.packages("rgeos")
library(rgeos) # centroids
library(dplyr)

# composite map with AK & HI
usa_map <- usa_composite()

# calculate the centroids for each state gCentroid(usa_map, byid=TRUE) %>%
as.data.frame() %>%
mutate(state=usa_map@data$iso_3166_2) -> centroids

# make it usable in ggplot2
usa_map <- fortify(usa_map)

View(usa_map)
t1 <- head(usa_map,n=5)
knitr::kable(t1, row.names=FALSE, align=c("l", "l", "r", "r", "r"))

#

# |long |lat | group| order| region|subregion |
# |:-|:|-:|-:|---:|:-|
# |-87.46201 |30.38968 | 1| 1| alabama|NA |
# |-87.48493 |30.37249 | 1| 2| alabama|NA |
# |-87.52503 |30.37249 | 1| 3| alabama|NA |
# |-87.53076 |30.33239 | 1| 4| alabama|NA |
# |-87.57087 |30.32665 | 1| 5| alabama|NA |

usa_map <- fortify(usa_map)
gg <- ggplot()
gg <- gg + geom_map(data=usa_map, map=usa_map,
aes(long, lat, map_id=id),
color="#2b2b2b", size=0.1, fill=NA)

gg <- gg + geom_text(data=centroids, aes(x, y, label=state), size=2) gg <- gg + 
coord_proj(us_laea_proj) gg <- gg + theme_map() gg




#/

This second is an alternative (h

Re: [R-sig-Geo] Help with simple Map of US states to predefined regions

2018-09-14 Thread Jérome Mathieu
Hi,

this might help you:

http://socviz.co/maps.html#maps
http://strimas.com/r/tidy-sf/
https://cran.r-project.org/web/packages/fiftystater/vignettes/fiftystater.html

Jerome





Le mer. 12 sept. 2018 à 20:27, Bill Poling  a écrit :
>
> Hi
>
> I have this df with three columns ProviderState, ProviderStateCode,
ProviderRegion I wanted to use to create a simple 5 color map
>
> I have reviewed fiftystater pkg and map pkg but not sure how to simply
take these three columns and plot a simple 5 color map based on the Region
the state is in?
>
> After looking at these and trying to apply these ideas to my data
>
https://cran.r-project.org/web/packages/fiftystater/vignettes/fiftystater.html
> https://cran.r-project.org/web/packages/maps/maps.pdf
>
> I found tutorial at:
https://uchicagoconsulting.wordpress.com/tag/r-ggplot2-maps-visualization/
>
> I used the tutorial data and subset in my regions
>
> So now I have come up with the 5 segmented maps and my question becomes
how to put this all into one map of the US?
>
>
> install.packages("maps")
> library(maps)
> library(ggplot2)
>
> #load us map data
> all_states <- map_data("state") View(all_states)
> #plot all states with ggplot
> p <- ggplot()
> p <- p + geom_polygon( data=all_states, aes(x=long, y=lat, group =
group),colour="white", fill="blue" )
> p
>
> #http://sape.inf.usi.ch/quick-reference/ggplot2/colour
>
> #Pacificstates
> Pacificstates <- subset(all_states, region %in% c( "alaska", "arizona",
"california", "hawaii", "nevada", "oregon","washington") )
> p <- ggplot()
> p <- p + geom_polygon( data=Pacificstates, aes(x=long, y=lat, group =
group),colour="white", fill="deepskyblue4" ) +
>   labs(title = "Pacificstates")
> p
>
> #Frontierstates
> Frontierstates <- subset(all_states, region %in% c( "colorado", "idaho",
"kansas", "montana", "new mexico", "oklahoma","texas", "utah", "wyoming") )
> p <- ggplot()
> p <- p + geom_polygon( data=Frontierstates, aes(x=long, y=lat, group =
group),colour="white", fill="dodgerblue1" ) +
>   labs(title = "FrontierStates")
> p
>
> #Midweststates
> Midweststates <- subset(all_states, region %in% c( "iowa", "illinois",
"indiana", "michigan", "minnesota", "missouri","north dakota", "nebraska",
"ohio","south dakota","wisconsin") )
> p <- ggplot()
> p <- p + geom_polygon( data=Midweststates, aes(x=long, y=lat, group =
group),colour="white", fill="dodgerblue1" ) +
>   labs(title = "MidwestStates")
> p
>
> #Southernstates
> Southernstates <- subset(all_states, region %in% c( "alabama",
"arkansas", "florida", "georgia", "kentucky", "louisiana","mississippi"
> ,"north carolina",
"south carolina","tennessee","virginia","west virginia") )
> p <- ggplot()
> p <- p + geom_polygon( data=Southernstates, aes(x=long, y=lat, group =
group),colour="white", fill="royalblue2" ) +
>   labs(title = "Southernstates")
> p
>
> # Northeaststates
> Northeaststates <- subset(all_states, region %in% c( "connecticut",
"district of columbia", "delaware", "massachusetts", "maryland",
"maine","new hampshire"
>  , "new jersey", "new
york","pennsylvania","rhode island","vermont") )
> p <- ggplot()
> p <- p + geom_polygon( data=Northeaststates, aes(x=long, y=lat, group =
group),colour="white", fill="dodgerblue4" ) +
>   labs(title = "Northeaststates")
> p
>
>
> #here is my my data but not used above
>
> str(Map1)
> Classes 'tbl_df', 'tbl' and 'data.frame':54 obs. of  3 variables:
> $ ProviderState: chr  "ALASKA" "ALABAMA" "ARKANSAS" "ARIZONA" ...
> $ ProviderStateCode: chr  "AK" "AL" "AR" "AZ" ...
> $ ProviderRegion   : chr  "Pacific" "South" "South" "Pacific" ...
> - attr(*, "spec")=List of 2
>   ..$ cols   :List of 3
>   .. ..$ ProviderState: list()
>   .. .. ..- attr(*, "class")= chr  "collector_character" "collector"
>   .. ..$ ProviderStateCode: list()
>   .. .. ..- attr(*, "class")= chr  "collector_character" "collector"
>   .. ..$ ProviderRegion   : list()
>   .. .. ..- attr(*, "class")= chr  "collector_character" "collector"
>   ..$ default: list()
>   .. ..- attr(*, "class")= chr  "collector_guess" "collector"
>   ..- attr(*, "class")= chr "col_spec"
>
> dput(Map1)
> structure(list(ProviderState = c("ALASKA", "ALABAMA", "ARKANSAS",
> "ARIZONA", "CALIFORNIA", "COLORADO", "CONNECTICUT", "DISTRICT OF
COLUMBIA",
> "DELAWARE", "FLORIDA", "GEORGIA", "GUAM", "HAWAII", "IOWA", "IDAHO",
> "ILLINOIS", "INDIANA", "KANSAS", "KENTUCKY", "LOUISIANA", "MASSACHUSETTS",
> "MARYLAND", "MAINE", "MICHIGAN", "MINNESOTA", "MISSOURI", "MISSISSIPPI",
> "MONTANA", "NORTH CAROLINA", "NORTH DAKOTA", "NEBRASKA", "NEW HAMPSHIRE",
> "NEW JERSEY", "NEW MEXICO", "NEVADA", "NEW YORK", "OHIO", "OKLAHOMA",
> "OREGON", "PENNSYLVANIA", "PUERTO RICO", "RHODE ISLAND", "SOUTH CAROLINA",
> "SOUTH DAKOTA", "TENNESSEE", "TEXAS", "UTAH", "VIRGINIA", "VIRGIN
ISLANDS",
> "VERMONT", "WASHINGTON", "WISCONSIN", "WEST VIRGINIA", "WYOMING"
> ), ProviderStateCode = c("AK", 

Re: [R-sig-Geo] Help with simple Map of US states to predefined regions

2018-09-13 Thread MacQueen, Don via R-sig-Geo
I know this is not a complete solution -- and it's a very different approach -- 
but it should at least show you one way to reliably get states colored by 
region.
I also left out Alaska and Hawaii.

require(sp)
require(rgdal)

## US Census Bureau Tiger file -- polygons of each US State
## try this URL for download
##   
https://www.census.gov/cgi-bin/geo/shapefiles/index.php?year=2017=States+%28and+equivalent%29

ustf <- readOGR('.', 'tl_2017_us_state', stringsAsFactors=FALSE)

## note, the Tiger file includes 6 additional territories
dim(ustf)
## [1] 56 14

## get rid of the extra six territories  (state.name comes with R)
cus <- subset(ustf, NAME %in% state.name)

## cheap rename
cus$state <- cus$NAME
cus$abb <- cus$STUSPS

## invent ridiculous groupings of states
cus$grp <- 'a'
cus$grp[11:20] <- 'b'
cus$grp[21:30] <- 'c'
cus$grp[31:40] <- 'd'
cus$grp[41:50] <- 'e'

## assign colors to the groups
cus$color <- 'red'
cus$color[cus$grp=='b'] <- 'green'
cus$color[cus$grp=='c'] <- 'blue'
cus$color[cus$grp=='d'] <- 'brown'
cus$color[cus$grp=='e'] <- 'cyan'

## exclude Alaska, Hawaii
cus <- subset(cus, !(state %in% c('Alaska','Hawaii')))

## get rid of extraneous variables (optional)
cus <- cus[ , c('state','REGION','abb', 'grp') ]

## plot colored by regions as defined in the Census Bureau Tiger file
plot(cus, col=cus$REGION, usePolypath=FALSE)
## color "1" is black, looks bad, do this instead
plot(cus, col=as.numeric(cus$REGION)+1, usePolypath=FALSE)
text(coordinates(cus), cus$abb, col='white', cex=0.75)

## colors specified by a color variable in the data
plot(cus, col=cus$color, usePolypath=FALSE)
text(coordinates(cus), cus$abb, col='white', cex=0.75)


--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
Lab cell 925-724-7509
 
 

On 9/12/18, 11:27 AM, "R-sig-Geo on behalf of Bill Poling" 
 wrote:

Hi

I have this df with three columns ProviderState, ProviderStateCode, 
ProviderRegion I wanted to use to create a simple 5 color map

I have reviewed fiftystater pkg and map pkg but not sure how to simply take 
these three columns and plot a simple 5 color map based on the Region the state 
is in?

After looking at these and trying to apply these ideas to my data

https://cran.r-project.org/web/packages/fiftystater/vignettes/fiftystater.html
https://cran.r-project.org/web/packages/maps/maps.pdf

I found tutorial at: 
https://uchicagoconsulting.wordpress.com/tag/r-ggplot2-maps-visualization/

I used the tutorial data and subset in my regions

So now I have come up with the 5 segmented maps and my question becomes how 
to put this all into one map of the US?


install.packages("maps")
library(maps)
library(ggplot2)

#load us map data
all_states <- map_data("state") View(all_states)
#plot all states with ggplot
p <- ggplot()
p <- p + geom_polygon( data=all_states, aes(x=long, y=lat, group = 
group),colour="white", fill="blue" )
p

#http://sape.inf.usi.ch/quick-reference/ggplot2/colour

#Pacificstates
Pacificstates <- subset(all_states, region %in% c( "alaska", "arizona", 
"california", "hawaii", "nevada", "oregon","washington") )
p <- ggplot()
p <- p + geom_polygon( data=Pacificstates, aes(x=long, y=lat, group = 
group),colour="white", fill="deepskyblue4" ) +
  labs(title = "Pacificstates")
p

#Frontierstates
Frontierstates <- subset(all_states, region %in% c( "colorado", "idaho", 
"kansas", "montana", "new mexico", "oklahoma","texas", "utah", "wyoming") )
p <- ggplot()
p <- p + geom_polygon( data=Frontierstates, aes(x=long, y=lat, group = 
group),colour="white", fill="dodgerblue1" ) +
  labs(title = "FrontierStates")
p

#Midweststates
Midweststates <- subset(all_states, region %in% c( "iowa", "illinois", 
"indiana", "michigan", "minnesota", "missouri","north dakota", "nebraska", 
"ohio","south dakota","wisconsin") )
p <- ggplot()
p <- p + geom_polygon( data=Midweststates, aes(x=long, y=lat, group = 
group),colour="white", fill="dodgerblue1" ) +
  labs(title = "MidwestStates")
p

#Southernstates
Southernstates <- subset(all_states, region %in% c( "alabama", "arkansas", 
"florida", "georgia", "kentucky", "louisiana","mississippi"
,"north carolina", 
"south carolina","tennessee","virginia","west virginia") )
p <- ggplot()
p <- p + geom_polygon( data=Southernstates, aes(x=long, y=lat, group = 
group),colour="white", fill="royalblue2" ) +
  labs(title = "Southernstates")
p

# Northeaststates
Northeaststates <- subset(all_states, region %in% c( "connecticut", 
"district of columbia", "delaware", "massachusetts", "maryland", "maine","new 
hampshire"
 , "new jersey", "new 
york","pennsylvania","rhode 

Re: [R-sig-Geo] Help with simple Map of US states with predefined regions Version 2

2018-09-13 Thread MacQueen, Don via R-sig-Geo
I know this is not a complete solution -- and it's a very different approach -- 
but it should at least show you a way to reliably get states colored by region.
(I also left out Alaska and Hawaii, since the point here is how to color the 
regions)

require(sp)
require(rgdal)

## US Census Bureau Tiger file -- polygons of each US State
## try this URL for download
##  
https://www.census.gov/cgi-bin/geo/shapefiles/index.php?year=2017=States+%28and+equivalent%29

## unzip to working directory ( '.' )
ustf <- readOGR('.', 'tl_2017_us_state', stringsAsFactors=FALSE)

## note, the Tiger file includes 6 additional territories
dim(ustf)
## [1] 56 14

## get rid of the extra six territories  (state.name comes with R)
cus <- subset(ustf, NAME %in% state.name)

## cheap rename
cus$state <- cus$NAME
cus$abb <- cus$STUSPS

## invent ridiculous groupings of states
cus$grp <- 'a'
cus$grp[11:20] <- 'b'
cus$grp[21:30] <- 'c'
cus$grp[31:40] <- 'd'
cus$grp[41:50] <- 'e'

## assign colors to the groups
cus$color <- 'red'
cus$color[cus$grp=='b'] <- 'green'
cus$color[cus$grp=='c'] <- 'blue'
cus$color[cus$grp=='d'] <- 'brown'
cus$color[cus$grp=='e'] <- 'cyan'

## exclude Alaska, Hawaii
cus <- subset(cus, !(state %in% c('Alaska','Hawaii')))

## get rid of extraneous variables (optional)
cus <- cus[ , c('state','REGION','abb', 'grp') ]

## plot colored by regions as defined in the Census Bureau Tiger file
plot(cus, col=cus$REGION, usePolypath=FALSE)

## color "1" is black, looks bad, do this instead
plot(cus, col=as.numeric(cus$REGION)+1, usePolypath=FALSE)
text(coordinates(cus), cus$abb, col='white', cex=0.75)

## colors specified by a color variable in the data
plot(cus, col=cus$color, usePolypath=FALSE)
text(coordinates(cus), cus$abb, col='white', cex=0.75)

(my preferred graphics device does not support Polypath, but probably most 
others do, so one can omit usePolypath=FALSE)

-Don

--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
Lab cell 925-724-7509
 
 

On 9/13/18, 5:17 AM, "R-sig-Geo on behalf of Bill Poling" 
 wrote:

Hi,

I hope someone can help me finalize this please.

I am coming close to what I need using variations from two ggplot2 
tutorials.

This first gives me the map of the US with AK & HI but I cannot figure out 
how to get my 5 regions colored


#https://stackoverflow.com/questions/38021188/how-to-draw-u-s-state-map-with-hi-and-ak-with-state-abbreviations-centered-us?rq=1


library(ggplot2)
install.packages("ggalt")
library(ggalt) # coord_proj
library(albersusa) # devtools::install_github("hrbrmstr/albersusa")
install.packages("ggthemes")
library(ggthemes)  # theme_map
install.packages("rgeos")
library(rgeos) # centroids
library(dplyr)

# composite map with AK & HI
usa_map <- usa_composite()

# calculate the centroids for each state gCentroid(usa_map, byid=TRUE) %>%
  as.data.frame() %>%
  mutate(state=usa_map@data$iso_3166_2) -> centroids

# make it usable in ggplot2
usa_map <- fortify(usa_map)

View(usa_map)
t1 <- head(usa_map,n=5)
knitr::kable(t1, row.names=FALSE, align=c("l", "l", "r", "r", "r"))

#

  # |long  |lat  | group| order|  region|subregion |
  # |:-|:|-:|-:|---:|:-|
  # |-87.46201 |30.38968 | 1| 1| alabama|NA|
  # |-87.48493 |30.37249 | 1| 2| alabama|NA|
  # |-87.52503 |30.37249 | 1| 3| alabama|NA|
  # |-87.53076 |30.33239 | 1| 4| alabama|NA|
  # |-87.57087 |30.32665 | 1| 5| alabama|NA|

usa_map <- fortify(usa_map)
gg <- ggplot()
gg <- gg + geom_map(data=usa_map, map=usa_map,
aes(long, lat, map_id=id),
color="#2b2b2b", size=0.1, fill=NA)

gg <- gg + geom_text(data=centroids, aes(x, y, label=state), size=2) gg <- 
gg + coord_proj(us_laea_proj) gg <- gg + theme_map() gg





#/

This second is an alternative (however not liking AK, not coming into 
the map like scenario one above) but also ignoring new Mexico (because 
recognizing a seventh field value) and I suspect it will do the same for new 
York and new jersey etc.. when I add them to the list.

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = 
dec,  :  line 12 did not have 6 elements

When I use newmexico (all one word) it appears white in the map like the 
other states not in the table statement


#https://stackoverflow.com/questions/3832/r-code-to-generating-map-of-us-states-with-specific-colors

library(ggplot2)


[R-sig-Geo] Help with simple Map of US states with predefined regions Version 2

2018-09-13 Thread Bill Poling
Hi,

I hope someone can help me finalize this please.

I am coming close to what I need using variations from two ggplot2 tutorials.

This first gives me the map of the US with AK & HI but I cannot figure out how 
to get my 5 regions colored

#https://stackoverflow.com/questions/38021188/how-to-draw-u-s-state-map-with-hi-and-ak-with-state-abbreviations-centered-us?rq=1


library(ggplot2)
install.packages("ggalt")
library(ggalt) # coord_proj
library(albersusa) # devtools::install_github("hrbrmstr/albersusa")
install.packages("ggthemes")
library(ggthemes)  # theme_map
install.packages("rgeos")
library(rgeos) # centroids
library(dplyr)

# composite map with AK & HI
usa_map <- usa_composite()

# calculate the centroids for each state gCentroid(usa_map, byid=TRUE) %>%
  as.data.frame() %>%
  mutate(state=usa_map@data$iso_3166_2) -> centroids

# make it usable in ggplot2
usa_map <- fortify(usa_map)

View(usa_map)
t1 <- head(usa_map,n=5)
knitr::kable(t1, row.names=FALSE, align=c("l", "l", "r", "r", "r"))

#

  # |long  |lat  | group| order|  region|subregion |
  # |:-|:|-:|-:|---:|:-|
  # |-87.46201 |30.38968 | 1| 1| alabama|NA|
  # |-87.48493 |30.37249 | 1| 2| alabama|NA|
  # |-87.52503 |30.37249 | 1| 3| alabama|NA|
  # |-87.53076 |30.33239 | 1| 4| alabama|NA|
  # |-87.57087 |30.32665 | 1| 5| alabama|NA|

usa_map <- fortify(usa_map)
gg <- ggplot()
gg <- gg + geom_map(data=usa_map, map=usa_map,
aes(long, lat, map_id=id),
color="#2b2b2b", size=0.1, fill=NA)

gg <- gg + geom_text(data=centroids, aes(x, y, label=state), size=2) gg <- gg + 
coord_proj(us_laea_proj) gg <- gg + theme_map() gg




#/

This second is an alternative (however not liking AK, not coming into the 
map like scenario one above) but also ignoring new Mexico (because recognizing 
a seventh field value) and I suspect it will do the same for new York and new 
jersey etc.. when I add them to the list.

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  : 
 line 12 did not have 6 elements

When I use newmexico (all one word) it appears white in the map like the other 
states not in the table statement

#https://stackoverflow.com/questions/3832/r-code-to-generating-map-of-us-states-with-specific-colors

library(ggplot2)

read.table(text="State.Code   regionSt_Abbr   Num_Estab  colors
  1  1   alaska   Ak13123#f7931e
  3  1   arizona  AZ18053#f7931e
  5  1   california   CA   143937#f7931e
  2  1   hawaii   HI   123456#f7931e
  4  1   nevada   NV   654321#f7931e
  6  1   oregon   OR   321456#f7931e
  7  1   washington   WA   456123#f7931e
  8  2   colorado CO   987654#787878
  9  2   idahoID   13549 #787878
 10  2   kansas   KS   94531 #787878
 11  2   montana  MT   456321#787878
 12  2   new mexico   NM 582310
#787878 <---Not liking new mexico, saying not 6
 13  2   oklahoma OK   214567#787878
 14  2   texasTX   675421#787878
 15  2   utah UT   754321#787878
 16  2   wyoming  WY   543124#787878 ",
stringsAsFactors=FALSE, header=TRUE, comment.char="") -> df

usa_map1 <- map_data("state")
t1 <- head(usa_map1,n=5)
knitr::kable(t1, row.names=FALSE, align=c("l", "l", "r", "r", "r"))
View(usa_map1)
#
#   |long  |lat  | group| order|  region|subregion |
#   |:-|:|-:|-:|---:|:-|
#   |-87.46201 |30.38968 | 1| 1| alabama|NA|
#   |-87.48493 |30.37249 | 1| 2| alabama|NA|
#   |-87.52503 |30.37249 | 1| 3| alabama|NA|
#   |-87.53076 |30.33239 | 1| 4| alabama|NA|
#   |-87.57087 |30.32665 | 1| 5| alabama|NA|



gg <- ggplot()
#View(gg)
gg <- gg + geom_map(data=usa_map1, map=usa_map1,
aes(long, lat, map_id=region),
color="#2b2b2b", size=0.15, fill=NA)

gg <- gg + geom_map(data=df, map=usa_map1,
aes(fill=colors, map_id=region),
color="#2b2b2b", size=0.15)


gg <- gg + geom_text(data=centroids, aes(x, y, label=state), size=2) gg <- gg + 

Re: [R-sig-Geo] help: Problem getting centroids inside lists

2018-09-12 Thread Ariel Fuentesdi
I understand, but I said "it doesn't work" because it gave an undesired
solution, but I'll try to be more explicit next time.
And I forgot to say that: s  <- 1: length(ct)

And thank you for your advice, but the answer of Vijay Lulla resolved my
problem.

Regards,
Ariel

2018-09-12 17:43 GMT-03:00 MacQueen, Don :

> On any R mailing list, whenever you say "it doesn't work", you should
> always copy exactly what R command you gave, and any error messages.
>
> First notice:
>
> > ct$a$two
> SpatialPoints:
>  lon lat
> [1,] -18  -2
> [2,] -16  50
> Coordinate Reference System (CRS) arguments: NA
>
> Then compare these:
>
> > coordinates(ct$a$two)
>  lon lat
> [1,] -18  -2
> [2,] -16  50
>
> > coordinates(slot(ct$a$two,'coords'))
>  lon lat
> [1,] -18  -2
> [2,] -16  50
>
> The results are the same. Why are you using the slot() function? There is
> no need, and it makes it more difficult to understand.
>
>
> You have assumed the mean() function will give you what you want when
> there are two points. It doesn't. Try it and see:
>
> > mean( coordinates(ct$a$two))
> [1] 3.5
>
> > mean(coordinates(slot(ct$a$two,'coords')))
>  [1] 3.5
>
> Replace the mean() function with a function that will give you the
> "centroid" of two points, however you want to define that centroid. Perhaps
> the means of the two columns? R has a function for that.
>
> -
> In this bit:
>
> ctply <- lapply(X = s, FUN = function(x) sapply(X = ct[[x]],
> FUN = function(y)
>
> Using X = s is wrong because you haven't defined or created s anywhere. X
> should be ct.
>
> Also, X = ct[[x]] is wrong. When the first FUN is executed, it will be
> supplied automatically with the whole of ct$a, then ct$b. Try
>
> ctply <- lapply(X = s, FUN = function(x) sapply(X = x,
> FUN = function(y)
>
> The whole thing is easier to understand and test if you define the
> functions outside the lapply and sapply calls.
>
> -Don
> --
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> 925-423-1062
> Lab cell 925-724-7509
>
>
>
> On 9/12/18, 11:42 AM, "R-sig-Geo on behalf of Ariel Fuentesdi" <
> r-sig-geo-boun...@r-project.org on behalf of ariel.fuente...@usach.cl>
> wrote:
>
> I went to a more general approach, that is:
>
> ctply <- lapply(X = s, FUN = function(x) sapply(X = ct[[x]],
>   FUN = function(y) if(length(y)>1) geosphere::centroid(slot(y,
> "coords"))
>   else sp::coordinates(slot(y, "coords"
>
> But now I want to add the case when they are only two elements. The
> dataset
> will be:
>
> ct <- list(a = list(one = data.frame(lon = c(-180, -160, -60), lat =
> c(-20,
> 5, 0)),
> two = data.frame(lon = c(-18, -16), lat = c(-2,
> 50))),
>b = list(one = data.frame(lon = c(-9, -8, -3), lat = c(-1,
> 25,
> 5)),
> two = data.frame(lon = c(-90), lat = c(-1
> coordinates(ct$a$one) <- ~lon+lat
> coordinates(ct$a$two) <- ~lon+lat
> coordinates(ct$b$one) <- ~lon+lat
> coordinates(ct$b$two) <- ~lon+lat
>
> And I did the following but it doesn't work:
>
> ctply <- lapply(X = s, FUN = function(x) sapply(X = ct[[x]],
> FUN = function(y)
> if(length(y)>2) geosphere::centroid(slot(y, "coords"))
> else if (length(y) ==
> 1)
> sp::coordinates(slot(y, "coords"))
> else
> mean(sp::coordinates(slot(y, "coords")
>
> I need the result of each element of the list will be a matrix of two
> rows
> per column (named: one, two). How do I fix it?
>
> Regards,
> Ariel
>
> 2018-09-10 17:29 GMT-03:00 MacQueen, Don :
>
> > If all of your data frames had enough points then this should work:
> >
> > myfun1 <- function(le) {
> >   list(one=geosphere::centroid(coordinates(le$one)),
> >two=geosphere::centroid(coordinates(le$two))
> >)
> > }
> >
> > lapply(ct, myfun1)
> >
> > To handle the one point case, try the following, which I think works
> with
> > your example data, but is untested if there just two points.
> > It also assumes the data frames are named 'one' and 'two', and will
> ignore
> > any others. To handle other names, I think you
> > could replace  $one  with  [[1]]  and  $two  with  [[2]]  .
> >
> > myfun <- function(le) {
> >   list(one=if (length(le$one)>1) geosphere::centroid(
> coordinates(le$one))
> > else coodinates(le$one),
> >two=if (length(le$two)>1) geosphere::centroid(
> coordinates(le$two))
> > else coordinates(le$two)
> >)
> > }
> >
> > lapply(ct, myfun)
> >
> >
> > To see a little bit of what's going on, try
>  

Re: [R-sig-Geo] help: Problem getting centroids inside lists

2018-09-12 Thread Vijay Lulla
Maybe the following function is what you're looking for?

getcentroids <- function(x1) {
  getcentroid <- function(x) {
coords <- slot(x, "coords")
numrows <- dim(coords)[1]
ret <- if(numrows == 2) {
  matrix(apply(coords,2,mean), nrow=1)
} else {
  if(numrows == 1) {
coords
  } else {
geosphere::centroid(coords)
  }
}
ret
  }

  r <- lapply(x1, function(x) as.data.frame(getcentroid(x)))

  ret <- matrix(unlist(r), ncol=2, byrow=TRUE)
  rownames(ret) <- names(r); colnames(ret) <- c("lon", "lat")

  ret
}

Now call it as lapply(ct, getcentroids)

HTH,
Vijay.

On Wed, Sep 12, 2018 at 2:42 PM Ariel Fuentesdi 
wrote:

> I went to a more general approach, that is:
>
> ctply <- lapply(X = s, FUN = function(x) sapply(X = ct[[x]],
>   FUN = function(y) if(length(y)>1) geosphere::centroid(slot(y,
> "coords"))
>   else sp::coordinates(slot(y, "coords"
>
> But now I want to add the case when they are only two elements. The dataset
> will be:
>
> ct <- list(a = list(one = data.frame(lon = c(-180, -160, -60), lat = c(-20,
> 5, 0)),
> two = data.frame(lon = c(-18, -16), lat = c(-2, 50))),
>b = list(one = data.frame(lon = c(-9, -8, -3), lat = c(-1, 25,
> 5)),
> two = data.frame(lon = c(-90), lat = c(-1
> coordinates(ct$a$one) <- ~lon+lat
> coordinates(ct$a$two) <- ~lon+lat
> coordinates(ct$b$one) <- ~lon+lat
> coordinates(ct$b$two) <- ~lon+lat
>
> And I did the following but it doesn't work:
>
> ctply <- lapply(X = s, FUN = function(x) sapply(X = ct[[x]],
> FUN = function(y)
> if(length(y)>2) geosphere::centroid(slot(y, "coords"))
> else if (length(y) == 1)
> sp::coordinates(slot(y, "coords"))
> else
> mean(sp::coordinates(slot(y, "coords")
>
> I need the result of each element of the list will be a matrix of two rows
> per column (named: one, two). How do I fix it?
>
> Regards,
> Ariel
>
> 2018-09-10 17:29 GMT-03:00 MacQueen, Don :
>
> > If all of your data frames had enough points then this should work:
> >
> > myfun1 <- function(le) {
> >   list(one=geosphere::centroid(coordinates(le$one)),
> >two=geosphere::centroid(coordinates(le$two))
> >)
> > }
> >
> > lapply(ct, myfun1)
> >
> > To handle the one point case, try the following, which I think works with
> > your example data, but is untested if there just two points.
> > It also assumes the data frames are named 'one' and 'two', and will
> ignore
> > any others. To handle other names, I think you
> > could replace  $one  with  [[1]]  and  $two  with  [[2]]  .
> >
> > myfun <- function(le) {
> >   list(one=if (length(le$one)>1) geosphere::centroid(coordinates(le$one))
> > else coodinates(le$one),
> >two=if (length(le$two)>1) geosphere::centroid(coordinates(le$two))
> > else coordinates(le$two)
> >)
> > }
> >
> > lapply(ct, myfun)
> >
> >
> > To see a little bit of what's going on, try
> >
> >   myfun(ct[[1]])
> >   myfun1(ct[[1]])
> >   myfun1(ct[[2]])
> >   myfun(ct[[2]])
> >
> >
> >
> > I would also verify that the length method for objects of class
> > SpatialPoints does return the number of points, as it appears to:
> >
> > > class(ct$a$two)
> > [1] "SpatialPoints"
> > attr(,"package")
> > [1] "sp"
> >
> > > length(ct$a$one)
> > [1] 3
> > > length(ct$a$two)
> > [1] 3
> > > length(ct$a$two)
> > [1] 3
> > > length(ct$b$two)
> > [1] 1
> >
> > --
> > Don MacQueen
> > Lawrence Livermore National Laboratory
> > 7000 East Ave., L-627
> > Livermore, CA 94550
> > 925-423-1062
> > Lab cell 925-724-7509
> >
> >
> >
> > On 9/10/18, 10:56 AM, "R-sig-Geo on behalf of Ariel Fuentesdi" <
> > r-sig-geo-boun...@r-project.org on behalf of ariel.fuente...@usach.cl>
> > wrote:
> >
> > Hi everyone,
> >
> > I have a list of coordinates called "ct" and I want to extract the
> > centroids of each sublist, but it only works when it has only 3 or
> more
> > points. In ct$b$two only has one point; in that case, I would rescue
> > that
> > point as If it were a centroid.
> >
> > This is what I did:
> >
> > library(dplyr)
> > library(geosphere)
> >
> > ct <- list(a = list(one = data.frame(lon = c(-180, -160, -60), lat =
> > c(-20,
> > 5, 0)),
> > two = data.frame(lon = c(-18, -16, -6), lat =
> > c(-2, 50,
> > 10))),
> >b = list(one = data.frame(lon = c(-9, -8, -3), lat = c(-1,
> > 25,
> > 5)),
> > two = data.frame(lon = c(-90), lat = c(-1
> >
> > coordinates(ct$a$one) <- ~lon+lat
> > coordinates(ct$a$two) <- ~lon+lat
> > coordinates(ct$b$one) <- ~lon+lat
> > coordinates(ct$b$two) <- ~lon+lat
> >
> > s <- 1:length(ct)
> > ctply <- list()
> > for (i in s){
> >  for (j in 1:length(ct[[i]])) {
> >   ctply[[i]][j] <- ifelse(test = 

Re: [R-sig-Geo] help: Problem getting centroids inside lists

2018-09-12 Thread Ariel Fuentesdi
I went to a more general approach, that is:

ctply <- lapply(X = s, FUN = function(x) sapply(X = ct[[x]],
  FUN = function(y) if(length(y)>1) geosphere::centroid(slot(y,
"coords"))
  else sp::coordinates(slot(y, "coords"

But now I want to add the case when they are only two elements. The dataset
will be:

ct <- list(a = list(one = data.frame(lon = c(-180, -160, -60), lat = c(-20,
5, 0)),
two = data.frame(lon = c(-18, -16), lat = c(-2, 50))),
   b = list(one = data.frame(lon = c(-9, -8, -3), lat = c(-1, 25,
5)),
two = data.frame(lon = c(-90), lat = c(-1
coordinates(ct$a$one) <- ~lon+lat
coordinates(ct$a$two) <- ~lon+lat
coordinates(ct$b$one) <- ~lon+lat
coordinates(ct$b$two) <- ~lon+lat

And I did the following but it doesn't work:

ctply <- lapply(X = s, FUN = function(x) sapply(X = ct[[x]],
FUN = function(y)
if(length(y)>2) geosphere::centroid(slot(y, "coords"))
else if (length(y) == 1)
sp::coordinates(slot(y, "coords"))
else
mean(sp::coordinates(slot(y, "coords")

I need the result of each element of the list will be a matrix of two rows
per column (named: one, two). How do I fix it?

Regards,
Ariel

2018-09-10 17:29 GMT-03:00 MacQueen, Don :

> If all of your data frames had enough points then this should work:
>
> myfun1 <- function(le) {
>   list(one=geosphere::centroid(coordinates(le$one)),
>two=geosphere::centroid(coordinates(le$two))
>)
> }
>
> lapply(ct, myfun1)
>
> To handle the one point case, try the following, which I think works with
> your example data, but is untested if there just two points.
> It also assumes the data frames are named 'one' and 'two', and will ignore
> any others. To handle other names, I think you
> could replace  $one  with  [[1]]  and  $two  with  [[2]]  .
>
> myfun <- function(le) {
>   list(one=if (length(le$one)>1) geosphere::centroid(coordinates(le$one))
> else coodinates(le$one),
>two=if (length(le$two)>1) geosphere::centroid(coordinates(le$two))
> else coordinates(le$two)
>)
> }
>
> lapply(ct, myfun)
>
>
> To see a little bit of what's going on, try
>
>   myfun(ct[[1]])
>   myfun1(ct[[1]])
>   myfun1(ct[[2]])
>   myfun(ct[[2]])
>
>
>
> I would also verify that the length method for objects of class
> SpatialPoints does return the number of points, as it appears to:
>
> > class(ct$a$two)
> [1] "SpatialPoints"
> attr(,"package")
> [1] "sp"
>
> > length(ct$a$one)
> [1] 3
> > length(ct$a$two)
> [1] 3
> > length(ct$a$two)
> [1] 3
> > length(ct$b$two)
> [1] 1
>
> --
> Don MacQueen
> Lawrence Livermore National Laboratory
> 7000 East Ave., L-627
> Livermore, CA 94550
> 925-423-1062
> Lab cell 925-724-7509
>
>
>
> On 9/10/18, 10:56 AM, "R-sig-Geo on behalf of Ariel Fuentesdi" <
> r-sig-geo-boun...@r-project.org on behalf of ariel.fuente...@usach.cl>
> wrote:
>
> Hi everyone,
>
> I have a list of coordinates called "ct" and I want to extract the
> centroids of each sublist, but it only works when it has only 3 or more
> points. In ct$b$two only has one point; in that case, I would rescue
> that
> point as If it were a centroid.
>
> This is what I did:
>
> library(dplyr)
> library(geosphere)
>
> ct <- list(a = list(one = data.frame(lon = c(-180, -160, -60), lat =
> c(-20,
> 5, 0)),
> two = data.frame(lon = c(-18, -16, -6), lat =
> c(-2, 50,
> 10))),
>b = list(one = data.frame(lon = c(-9, -8, -3), lat = c(-1,
> 25,
> 5)),
> two = data.frame(lon = c(-90), lat = c(-1
>
> coordinates(ct$a$one) <- ~lon+lat
> coordinates(ct$a$two) <- ~lon+lat
> coordinates(ct$b$one) <- ~lon+lat
> coordinates(ct$b$two) <- ~lon+lat
>
> s <- 1:length(ct)
> ctply <- list()
> for (i in s){
>  for (j in 1:length(ct[[i]])) {
>   ctply[[i]][j] <- ifelse(test = lengths(ct[[i]][1]) > 2, yes =
> sapply(X =
> ct[[i]][j],
> FUN = function(y) geosphere::centroid(slot(y, "coords"))), no =
> ct[[i]][j] )
>  }
> }
>
> Thanks in advance
>
> Regards,
> Ariel
>
> [[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


[R-sig-Geo] Help with simple Map of US states to predefined regions

2018-09-12 Thread Bill Poling
Hi

I have this df with three columns ProviderState, ProviderStateCode, 
ProviderRegion I wanted to use to create a simple 5 color map

I have reviewed fiftystater pkg and map pkg but not sure how to simply take 
these three columns and plot a simple 5 color map based on the Region the state 
is in?

After looking at these and trying to apply these ideas to my data
https://cran.r-project.org/web/packages/fiftystater/vignettes/fiftystater.html
https://cran.r-project.org/web/packages/maps/maps.pdf

I found tutorial at: 
https://uchicagoconsulting.wordpress.com/tag/r-ggplot2-maps-visualization/

I used the tutorial data and subset in my regions

So now I have come up with the 5 segmented maps and my question becomes how to 
put this all into one map of the US?


install.packages("maps")
library(maps)
library(ggplot2)

#load us map data
all_states <- map_data("state") View(all_states)
#plot all states with ggplot
p <- ggplot()
p <- p + geom_polygon( data=all_states, aes(x=long, y=lat, group = 
group),colour="white", fill="blue" )
p

#http://sape.inf.usi.ch/quick-reference/ggplot2/colour

#Pacificstates
Pacificstates <- subset(all_states, region %in% c( "alaska", "arizona", 
"california", "hawaii", "nevada", "oregon","washington") )
p <- ggplot()
p <- p + geom_polygon( data=Pacificstates, aes(x=long, y=lat, group = 
group),colour="white", fill="deepskyblue4" ) +
  labs(title = "Pacificstates")
p

#Frontierstates
Frontierstates <- subset(all_states, region %in% c( "colorado", "idaho", 
"kansas", "montana", "new mexico", "oklahoma","texas", "utah", "wyoming") )
p <- ggplot()
p <- p + geom_polygon( data=Frontierstates, aes(x=long, y=lat, group = 
group),colour="white", fill="dodgerblue1" ) +
  labs(title = "FrontierStates")
p

#Midweststates
Midweststates <- subset(all_states, region %in% c( "iowa", "illinois", 
"indiana", "michigan", "minnesota", "missouri","north dakota", "nebraska", 
"ohio","south dakota","wisconsin") )
p <- ggplot()
p <- p + geom_polygon( data=Midweststates, aes(x=long, y=lat, group = 
group),colour="white", fill="dodgerblue1" ) +
  labs(title = "MidwestStates")
p

#Southernstates
Southernstates <- subset(all_states, region %in% c( "alabama", "arkansas", 
"florida", "georgia", "kentucky", "louisiana","mississippi"
,"north carolina", "south 
carolina","tennessee","virginia","west virginia") )
p <- ggplot()
p <- p + geom_polygon( data=Southernstates, aes(x=long, y=lat, group = 
group),colour="white", fill="royalblue2" ) +
  labs(title = "Southernstates")
p

# Northeaststates
Northeaststates <- subset(all_states, region %in% c( "connecticut", "district 
of columbia", "delaware", "massachusetts", "maryland", "maine","new hampshire"
 , "new jersey", "new 
york","pennsylvania","rhode island","vermont") )
p <- ggplot()
p <- p + geom_polygon( data=Northeaststates, aes(x=long, y=lat, group = 
group),colour="white", fill="dodgerblue4" ) +
  labs(title = "Northeaststates")
p


#here is my my data but not used above

str(Map1)
Classes 'tbl_df', 'tbl' and 'data.frame':54 obs. of  3 variables:
$ ProviderState: chr  "ALASKA" "ALABAMA" "ARKANSAS" "ARIZONA" ...
$ ProviderStateCode: chr  "AK" "AL" "AR" "AZ" ...
$ ProviderRegion   : chr  "Pacific" "South" "South" "Pacific" ...
- attr(*, "spec")=List of 2
  ..$ cols   :List of 3
  .. ..$ ProviderState: list()
  .. .. ..- attr(*, "class")= chr  "collector_character" "collector"
  .. ..$ ProviderStateCode: list()
  .. .. ..- attr(*, "class")= chr  "collector_character" "collector"
  .. ..$ ProviderRegion   : list()
  .. .. ..- attr(*, "class")= chr  "collector_character" "collector"
  ..$ default: list()
  .. ..- attr(*, "class")= chr  "collector_guess" "collector"
  ..- attr(*, "class")= chr "col_spec"

dput(Map1)
structure(list(ProviderState = c("ALASKA", "ALABAMA", "ARKANSAS",
"ARIZONA", "CALIFORNIA", "COLORADO", "CONNECTICUT", "DISTRICT OF COLUMBIA",
"DELAWARE", "FLORIDA", "GEORGIA", "GUAM", "HAWAII", "IOWA", "IDAHO",
"ILLINOIS", "INDIANA", "KANSAS", "KENTUCKY", "LOUISIANA", "MASSACHUSETTS",
"MARYLAND", "MAINE", "MICHIGAN", "MINNESOTA", "MISSOURI", "MISSISSIPPI",
"MONTANA", "NORTH CAROLINA", "NORTH DAKOTA", "NEBRASKA", "NEW HAMPSHIRE",
"NEW JERSEY", "NEW MEXICO", "NEVADA", "NEW YORK", "OHIO", "OKLAHOMA",
"OREGON", "PENNSYLVANIA", "PUERTO RICO", "RHODE ISLAND", "SOUTH CAROLINA",
"SOUTH DAKOTA", "TENNESSEE", "TEXAS", "UTAH", "VIRGINIA", "VIRGIN ISLANDS",
"VERMONT", "WASHINGTON", "WISCONSIN", "WEST VIRGINIA", "WYOMING"
), ProviderStateCode = c("AK", "AL", "AR", "AZ", "CA", "CO",
"CT", "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN",
"KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MS", "MT",
"NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR",
"PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VI", "VT",
"WA", "WI", "WV", "WY"), ProviderRegion = c("Pacific", "South",
"South", "Pacific", "Pacific", 

Re: [R-sig-Geo] help: Problem getting centroids inside lists

2018-09-10 Thread MacQueen, Don via R-sig-Geo
If all of your data frames had enough points then this should work:

myfun1 <- function(le) {
  list(one=geosphere::centroid(coordinates(le$one)),
   two=geosphere::centroid(coordinates(le$two))
   )
}

lapply(ct, myfun1)

To handle the one point case, try the following, which I think works with your 
example data, but is untested if there just two points.
It also assumes the data frames are named 'one' and 'two', and will ignore any 
others. To handle other names, I think you
could replace  $one  with  [[1]]  and  $two  with  [[2]]  .

myfun <- function(le) {
  list(one=if (length(le$one)>1) geosphere::centroid(coordinates(le$one)) else 
coodinates(le$one),
   two=if (length(le$two)>1) geosphere::centroid(coordinates(le$two)) else 
coordinates(le$two)
   )
}

lapply(ct, myfun)


To see a little bit of what's going on, try

  myfun(ct[[1]])
  myfun1(ct[[1]])
  myfun1(ct[[2]])
  myfun(ct[[2]])



I would also verify that the length method for objects of class SpatialPoints 
does return the number of points, as it appears to:

> class(ct$a$two)
[1] "SpatialPoints"
attr(,"package")
[1] "sp"

> length(ct$a$one)
[1] 3
> length(ct$a$two)
[1] 3
> length(ct$a$two)
[1] 3
> length(ct$b$two)
[1] 1

--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
Lab cell 925-724-7509
 
 

On 9/10/18, 10:56 AM, "R-sig-Geo on behalf of Ariel Fuentesdi" 
 wrote:

Hi everyone,

I have a list of coordinates called "ct" and I want to extract the
centroids of each sublist, but it only works when it has only 3 or more
points. In ct$b$two only has one point; in that case, I would rescue that
point as If it were a centroid.

This is what I did:

library(dplyr)
library(geosphere)

ct <- list(a = list(one = data.frame(lon = c(-180, -160, -60), lat = c(-20,
5, 0)),
two = data.frame(lon = c(-18, -16, -6), lat = c(-2, 50,
10))),
   b = list(one = data.frame(lon = c(-9, -8, -3), lat = c(-1, 25,
5)),
two = data.frame(lon = c(-90), lat = c(-1

coordinates(ct$a$one) <- ~lon+lat
coordinates(ct$a$two) <- ~lon+lat
coordinates(ct$b$one) <- ~lon+lat
coordinates(ct$b$two) <- ~lon+lat

s <- 1:length(ct)
ctply <- list()
for (i in s){
 for (j in 1:length(ct[[i]])) {
  ctply[[i]][j] <- ifelse(test = lengths(ct[[i]][1]) > 2, yes = sapply(X =
ct[[i]][j],
FUN = function(y) geosphere::centroid(slot(y, "coords"))), no =
ct[[i]][j] )
 }
}

Thanks in advance

Regards,
Ariel

[[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


[R-sig-Geo] help regarding methodology

2018-08-10 Thread Monica Kundu
I want to work on conditional probability using spatial analysis. To be
more precise,  as in one event depends on the other but not vice versa and
I want to prove this relation spatially. what methodology I can use.

[[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

2018-05-14 Thread Bede-Fazekas Ákos

Dear Soufianou,
this is just a framework. Let's say that you have a vector ('variables') 
containing the name of the environmental variables.


library(raster)
library(dismo)
library(corrplot)

for (variable in variables) {
    assign(variable, raster(paste0(variable, ".asc"))
}
environment <- brick(variables)
environment_standardized <- data.frame(scale(x = 
as.data.frame(environment), center = TRUE, scale = TRUE))


correlation_matrix <- cor(environment_standardized, use = "na.or.complete")
corrplot(corr = correlation_matrix)
VIF <- vif(environment_standardized)
CN <- kappa(na.omit(environment_standardized), exact = TRUE)
# You can select variables that fulfill your criteria about correlation 
structure

selected_variables <- variables[c()] # subsetting

maxent(x = environment[[selected_variables]] , p = presence_points)

HTH,
Ákos Bede-Fazekas
Hungarian Academy of Sciences

2018.05.14. 12:28 keltezéssel, Soufianou Abou via R-sig-Geo írta:

Dear Rolf Turner,

  I have points of presence of cowpea in Niger in CSV format; in addition to 
other variables (soil texture, soil pH, altitude, I downloaded from worldclim 
archives, the 19 environmental variables, I cut them all at the Niger scale and 
I converted them under ASCUI format. The idea for me is to choose the best 
variables to include in the model.
  NB. I'm using Maxent model, but I'm not good in R software.

Merci














SADDA Abou-Soufianou

--

Doctorant

Université Dan Dicko Dankoulodo deMaradi-Niger

BP 465 120, avenue MamanKoraou- ADS

    &

Institut d’Ecologie et des Sciencesde l’Environnement de Paris (iEES-Paris)

Centre IRD France Nord-(iEES Paris)-32,av.Henri Varangnat 93143 BONDY cedex.

|
Lien: https://ieesparis.ufr918.upmc.fr/index.php?page=fiche=378=1


  abousoufia...@gmail.com

GSM : Niger : (+227) 96-26-99-87/91-56-35-19 ; France (+ 33)  07-55-79-39-93

  
   |
  
   |











 Le lundi 14 mai 2018 à 12:05:40 UTC+2, Rolf Turner 
 a écrit :



Please keep your posts "on-list".  You are much more likely to get a
useful answer that way.  There are many others on the list whose
knowledge and insight are far greater than mine.

I have therefore cc-ed the list in this reply.

On 14/05/18 21:48, Soufianou Abou wrote:


Thank you for advice, Rolf Turner

My question is as follows:

I'd use maxent to model the potential distribution of cowpea on the
basis of the only presence data. Indeed, I have acquired a number of
environmental variables and bioclimatic regarding my area of study. But
to choose the most contributive variables in the model; I would like to
make a correlation analysis of these. On this, could you explain to me
the step by step procedures to follow in R? I would like to say scripts
for:- compile and call all environmental variables;- run the correlation
test to select the least correlated ones.

As I said before, I don't think this is the right approach, but I can't
be sure without knowing more about your data.  I find your description
to be vague.

How are your data stored?  What information do you have about the
"distribution of cowpea".  Do you have *points* where cowpea is present
or more extensive *regions* where it is present?  (And could these
regions be "considered to be points" on the scale of interest?) How are
your predictors stored?  Are the values of these predictors known at
every point of your study area?  Can you show us a bit of your data (use
the function dput() to include *a small sample* of your data in the body
of your email).

If you insist on mucking about with correlation and testing, perhaps the
function cor.test() will give you what you want.  I reiterate however
that this seems to me to be a wrong approach.

cheers,

Rolf Turner



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


[R-sig-Geo] Help

2018-05-14 Thread Soufianou Abou via R-sig-Geo
Dear Rolf Turner,

 I have points of presence of cowpea in Niger in CSV format; in addition to 
other variables (soil texture, soil pH, altitude, I downloaded from worldclim 
archives, the 19 environmental variables, I cut them all at the Niger scale and 
I converted them under ASCUI format. The idea for me is to choose the best 
variables to include in the model.
 NB. I'm using Maxent model, but I'm not good in R software.

Merci














SADDA Abou-Soufianou

--

Doctorant

Université Dan Dicko Dankoulodo deMaradi-Niger

BP 465 120, avenue MamanKoraou- ADS

   &

Institut d’Ecologie et des Sciencesde l’Environnement de Paris (iEES-Paris)

Centre IRD France Nord-(iEES Paris)-32,av.Henri Varangnat 93143 BONDY cedex.

|  
Lien: https://ieesparis.ufr918.upmc.fr/index.php?page=fiche=378=1


 abousoufia...@gmail.com

GSM : Niger : (+227) 96-26-99-87/91-56-35-19 ; France (+ 33)  07-55-79-39-93

 
  |  
 
  |










Le lundi 14 mai 2018 à 12:05:40 UTC+2, Rolf Turner 
 a écrit :  



Please keep your posts "on-list".  You are much more likely to get a 
useful answer that way.  There are many others on the list whose 
knowledge and insight are far greater than mine.

I have therefore cc-ed the list in this reply.

On 14/05/18 21:48, Soufianou Abou wrote:

> Thank you for advice, Rolf Turner
> 
> My question is as follows:
> 
> I'd use maxent to model the potential distribution of cowpea on the 
> basis of the only presence data. Indeed, I have acquired a number of 
> environmental variables and bioclimatic regarding my area of study. But 
> to choose the most contributive variables in the model; I would like to 
> make a correlation analysis of these. On this, could you explain to me 
> the step by step procedures to follow in R? I would like to say scripts 
> for:- compile and call all environmental variables;- run the correlation
> test to select the least correlated ones.

As I said before, I don't think this is the right approach, but I can't 
be sure without knowing more about your data.  I find your description
to be vague.

How are your data stored?  What information do you have about the 
"distribution of cowpea".  Do you have *points* where cowpea is present 
or more extensive *regions* where it is present?  (And could these 
regions be "considered to be points" on the scale of interest?) How are 
your predictors stored?  Are the values of these predictors known at 
every point of your study area?  Can you show us a bit of your data (use 
the function dput() to include *a small sample* of your data in the body 
of your email).

If you insist on mucking about with correlation and testing, perhaps the 
function cor.test() will give you what you want.  I reiterate however
that this seems to me to be a wrong approach.

cheers,

Rolf Turner

-- 
Technical Editor ANZJS
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


[R-sig-Geo] Help

2018-05-14 Thread Soufianou Abou via R-sig-Geo
Bonjour , j'aimerais utiliser  maxent pour modéliser la distribution 
potentielle du niébé sur la base des données de présence seuls. En effet, jai 
acquis un certains nombre de variables environnementales et bioclimatiques 
concernant ma zone d'étude.  Mais pour choisir les variables les plus 
contributives dans le modèle; j'aimerai faire une analyse de correlation de 
celles-ci. Sur ce, pourriez vous m'expliquer etape par etape les procedures à 
suivre sous R ? J'aimerais dire par là le scripts pour:  -compiler et 
appeler toutes les variables environnementales et les données d'occurence; -
executer le tester de correlation;-pour faire une analyse discriminante?

Merci par avance














SADDA Abou-Soufianou











[[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 about gstat's functions for spatio temporal data interpolation

2018-05-13 Thread Edzer Pebesma
Dear Bruno,

you'll find everything at https://github.com/edzer/gstat

On 05/12/2018 09:05 PM, Bruno Sesti wrote:
> Hi, I am trying to do spatio-temporal kriging and I am interested
> especially in the software implementation of the algorithm and of data
> analysis. I saw that R have many libraries and routines to perform spatial
> and spatii-temporal kriging. I would like to know if it could be possible
> to get the source code of some functions that package gstat offers to
> perform spatio-temporal kriging, that are:
> variogramST(), vgmST(), fit.StVariogram().
> 
> Kind regards.
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

-- 
Edzer Pebesma
Institute for Geoinformatics
Heisenbergstrasse 2, 48151 Muenster, Germany
Phone: +49 251 8333081

___
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'

2018-04-14 Thread Roger Bivand

On Sat, 14 Apr 2018, Sarah Goslee wrote:


Hi,

It's pretty much impossible, since we don't know what GIS software you
used, what commands, what R package and code, or what your data look
like.

As a starting point, I'd suggest carefully rereading the help files
for both the GIS and the R functions, to make sure that they are doing
the same thing, and what you expect them to, and to review your data
in both places to ensure that it is the same values and projection,
etc. It is entirely possible that one software is scaling your data
for you automatically, or some other processing step that is not
duplicated by the other software.

If trying those things doesn't clarify it for you, then please post
back to the list with more information about the software and data
you're using.


Yes, the problem is most likely that the weights and data are the same, 
but in GIS or R the data are sorted differently than the weights. 
Alternatively, the weights may be different for the same data. For R, it 
would help to see how you constructed the weights object. If the GIS is 
ArcGIS, for the same weights and data, we know what differences may be 
expected, and any such differences would not affect your conclusion.


Roger



Sarah

On Sat, Apr 14, 2018 at 1:18 AM, Yalemzewod Gelaw  wrote:

Hi

I tried to compute the Moran's I statistics using GIS and R. However, I got
different values.

Could you please brief me how the difference can occurs?

Using GIS

 Global Moran's I Summary

Moran's Index:   0.151485

Expected Index:  -0.007692

Variance:0.001040

z-score: 4.935027

p-value: 0.01



Using R

Moran I test under randomisation

data:  Dat$allprop

weights: Xlist

Moran I statistic standard deviate = 0.82453, p-value = 0.4096

alternative hypothesis: two.sided

sample estimates:

Moran I statistic   Expectation  Variance

  0.034154753  -0.007299270   0.002527644

NB: in the neighbour links there are 2 regions with no links


Thank you for any help



*Regards, *

Yalem







--
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


Re: [R-sig-Geo] 'help'

2018-04-14 Thread Sarah Goslee
Hi,

It's pretty much impossible, since we don't know what GIS software you
used, what commands, what R package and code, or what your data look
like.

As a starting point, I'd suggest carefully rereading the help files
for both the GIS and the R functions, to make sure that they are doing
the same thing, and what you expect them to, and to review your data
in both places to ensure that it is the same values and projection,
etc. It is entirely possible that one software is scaling your data
for you automatically, or some other processing step that is not
duplicated by the other software.

If trying those things doesn't clarify it for you, then please post
back to the list with more information about the software and data
you're using.

Sarah

On Sat, Apr 14, 2018 at 1:18 AM, Yalemzewod Gelaw  wrote:
> Hi
>
> I tried to compute the Moran's I statistics using GIS and R. However, I got
> different values.
>
> Could you please brief me how the difference can occurs?
>
> Using GIS
>
>  Global Moran's I Summary
>
> Moran's Index:   0.151485
>
> Expected Index:  -0.007692
>
> Variance:0.001040
>
> z-score: 4.935027
>
> p-value: 0.01
>
>
>
> Using R
>
> Moran I test under randomisation
>
> data:  Dat$allprop
>
> weights: Xlist
>
> Moran I statistic standard deviate = 0.82453, p-value = 0.4096
>
> alternative hypothesis: two.sided
>
> sample estimates:
>
> Moran I statistic   Expectation  Variance
>
>   0.034154753  -0.007299270   0.002527644
>
> NB: in the neighbour links there are 2 regions with no links
>
>
> Thank you for any help
>
>
>
> *Regards, *
>
> Yalem



-- 
Sarah Goslee
http://www.functionaldiversity.org

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


[R-sig-Geo] 'help'

2018-04-13 Thread Yalemzewod Gelaw
Hi

I tried to compute the Moran's I statistics using GIS and R. However, I got
different values.

Could you please brief me how the difference can occurs?

Using GIS

 Global Moran's I Summary

Moran's Index:   0.151485

Expected Index:  -0.007692

Variance:0.001040

z-score: 4.935027

p-value: 0.01



Using R

Moran I test under randomisation

data:  Dat$allprop

weights: Xlist

Moran I statistic standard deviate = 0.82453, p-value = 0.4096

alternative hypothesis: two.sided

sample estimates:

Moran I statistic   Expectation  Variance

  0.034154753  -0.007299270   0.002527644

NB: in the neighbour links there are 2 regions with no links


Thank you for any help



*Regards, *

Yalem

[[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

2018-04-05 Thread Andrew Duff
Shouldn't this line be

xlist <- nb2listw(neighbours,glist = NULL,style = "W",zero.policy =TRUE)


instead of


xlist <- nb2listw(neighbours,glist = NULL,style = "W",zero.policy =TRU)

?



On Wed, Apr 4, 2018 at 9:44 PM, Yalemzewod Gelaw 
wrote:

> I am a new student to R learning for spatial analysis. I was hoping
> someone could help me with the
> error message I keep getting when I try to convert the neighbour data to a
> listw object use the nb2listw()  function.
>
> plot(xw_nbq, coords,add=TRUE,col="red")> summary(xw_nbq)
>
>
> Neighbour list object:
> Number of regions: 140
> Number of nonzero links: 680
> Percentage nonzero weights: 3.469388
> Average number of links: 4.857143
> 2 regions with no links:
> 3 138
> Link number distribution:
>
>  0  1  2  3  4  5  6  7  8  9
>  2  6  4 16 32 35 17 13 13  2
> 6 least connected regions:
> 11 32 57 117 124 137 with 1 link
> 2 most connected regions:
> 28 71 with 9 links
>
> ​when I try to run nb2listw, i got repated error following the below error
> message. ​
>
> xlist <- nb2listw(neighbours,glist = NULL,style = "W",zero.policy =TRU) > 
> summary.listw(xlist)
> Error in summary.listw(xlist) : regions with no neighbours found, use
> zero.policy=TRUE
>
> I wonder if someone advises me how to fix the error message from my
> working directory
> ​
>
>
> *Regards, *
>
> Yalem
>
> ___
> 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] help

2018-04-05 Thread Roger Bivand

On Thu, 5 Apr 2018, Yalemzewod Gelaw wrote:


I am a new student to R learning for spatial analysis. I was hoping someone
could help me with the
error message I keep getting when I try to convert the neighbour data to a
listw object use the nb2listw()  function.

plot(xw_nbq, coords,add=TRUE,col="red")> summary(xw_nbq)


Neighbour list object:
Number of regions: 140
Number of nonzero links: 680
Percentage nonzero weights: 3.469388
Average number of links: 4.857143
2 regions with no links:
3 138
Link number distribution:

0  1  2  3  4  5  6  7  8  9
2  6  4 16 32 35 17 13 13  2
6 least connected regions:
11 32 57 117 124 137 with 1 link
2 most connected regions:
28 71 with 9 links

​when I try to run nb2listw, i got repated error following the below error
message. ​

xlist <- nb2listw(neighbours,glist = NULL,style = "W",zero.policy
=TRU) > summary.listw(xlist)
Error in summary.listw(xlist) : regions with no neighbours found, use
zero.policy=TRUE


Please do not send HTML-formatted messages.

You need to continue using zero.policy=TRUE when using an object created 
with no-neighbour observations. You can also set a pre-session global 
option using set.ZeroPolicyOption(TRUE), which is checked first in 
functions using the zero.policy= argument. set.ZeroPolicyOption(TRUE) 
outputs the value of get.ZeroPolicyOption() before making the change.


You should always find out why you have no-neighbour observations. From 
your attached image, it looks as though you have a faulty set of polygons, 
and have used poly2nb() to find border contiguities. My guess is that the 
polygons with no neighbours have borders that almost touch - look at the 
snap= argument in poly2nb(). There are also other near-contiguities to be 
found - had the input boundaries been line-generalized?


Roger



I wonder if someone advises me how to fix the error message from my working
directory
​


*Regards, *

Yalem



--
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


[R-sig-Geo] help

2018-04-04 Thread Yalemzewod Gelaw
I am a new student to R learning for spatial analysis. I was hoping someone
could help me with the
error message I keep getting when I try to convert the neighbour data to a
listw object use the nb2listw()  function.

plot(xw_nbq, coords,add=TRUE,col="red")> summary(xw_nbq)


Neighbour list object:
Number of regions: 140
Number of nonzero links: 680
Percentage nonzero weights: 3.469388
Average number of links: 4.857143
2 regions with no links:
3 138
Link number distribution:

 0  1  2  3  4  5  6  7  8  9
 2  6  4 16 32 35 17 13 13  2
6 least connected regions:
11 32 57 117 124 137 with 1 link
2 most connected regions:
28 71 with 9 links

​when I try to run nb2listw, i got repated error following the below error
message. ​

xlist <- nb2listw(neighbours,glist = NULL,style = "W",zero.policy
=TRU) > summary.listw(xlist)
Error in summary.listw(xlist) : regions with no neighbours found, use
zero.policy=TRUE

I wonder if someone advises me how to fix the error message from my working
directory
​


*Regards, *

Yalem
___
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 installing lwgeom on macOS

2018-02-26 Thread Patrick Schratz
Hi Kent,

brew install geos && brew install postgis (for lwgeom) works for me.

On Feb 25 2018, at 8:33 pm, Kent Johnson  wrote:
>
> I am trying to install lwgeom 0.1-4 from source on macOS 10.13.3.
> First try:
> R CMD INSTALL lwgeom_0.1-4.tar.gz
> ...
> checking for geos-config... no
> no
> configure: error: geos-config not found or not executable.
>
> Second try:
> R CMD INSTALL lwgeom_0.1-4.tar.gz
> --configure-args='-with-geos-config=/Library/Frameworks/GEOS.framework/Versions/3/unix/bin/geos-config'
> ...
> configure: geos-config set to
> /Library/Frameworks/GEOS.framework/Versions/3/unix/bin/geos-config
> checking geos-config exists... yes
> checking geos-config executable... yes
> checking geos-config usability... yes
> configure: GEOS: 3.6.1
> checking GEOS version >= 3.3.0... yes
> checking geos_c.h usability... no
> checking geos_c.h presence... no
> checking for geos_c.h... no
> configure: error: geos_c.h not found in given locations.
>
> I do have liblwgeom installed as part of Postgres.app. I have tried adding
> --with-liblwgeom=/Applications/Postgres.app/Contents/Versions/10/lib/liblwgeom-2.4.0.dylib
> to --configure-args with the same failure.
>
> I have the framework version of GEOS installed from kyngchaos and tried
> adding
> --configure-vars='CPPFLAGS=-I/Library/Frameworks/GEOS.framework/Versions/3/Headers'
> with the same failure.
>
> I don't really know what I'm doing here so any help is appreciated. FWIW
> I'm installing lwgeom to get access to the st_make_valid() function.
>
> Thank you!
> Kent Johnson
>
> [[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] Help installing lwgeom on macOS

2018-02-25 Thread Kent Johnson
This seems to work:

R CMD INSTALL lwgeom_0.1-4.tar.gz
--configure-args='-with-geos-config=/Library/Frameworks/GEOS.framework/Versions/3/unix/bin/geos-config
--with-liblwgeom=/Applications/Postgres.app/Contents/Versions/10/lib/liblwgeom-2.4.0.dylib'
--configure-vars='PKG_CPPFLAGS="-I/Library/Frameworks/GEOS.framework/Versions/3/unix/include
-I/Library/Frameworks/PROJ.framework/Versions/4/unix/include"' -d

Kent

On Sun, Feb 25, 2018 at 2:33 PM, Kent Johnson  wrote:

> I am trying to install lwgeom 0.1-4 from source on macOS 10.13.3.
>
> First try:
> R CMD INSTALL lwgeom_0.1-4.tar.gz
> ...
> checking for geos-config... no
> no
> configure: error: geos-config not found or not executable.
>
> Second try:
> R CMD INSTALL lwgeom_0.1-4.tar.gz --configure-args='-with-geos-
> config=/Library/Frameworks/GEOS.framework/Versions/3/unix/bin/geos-config'
> ...
> configure: geos-config set to /Library/Frameworks/GEOS.
> framework/Versions/3/unix/bin/geos-config
> checking geos-config exists... yes
> checking geos-config executable... yes
> checking geos-config usability... yes
> configure: GEOS: 3.6.1
> checking GEOS version >= 3.3.0... yes
> checking geos_c.h usability... no
> checking geos_c.h presence... no
> checking for geos_c.h... no
> configure: error: geos_c.h not found in given locations.
>
> I do have liblwgeom installed as part of Postgres.app. I have tried adding
> --with-liblwgeom=/Applications/Postgres.app/Contents/Versions/10/lib/
> liblwgeom-2.4.0.dylib
> to --configure-args with the same failure.
>
> I have the framework version of GEOS installed from kyngchaos and tried
> adding
> --configure-vars='CPPFLAGS=-I/Library/Frameworks/GEOS.
> framework/Versions/3/Headers'
> with the same failure.
>
> I don't really know what I'm doing here so any help is appreciated. FWIW
> I'm installing lwgeom to get access to the st_make_valid() function.
>
> Thank you!
> Kent Johnson
>

[[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] Help installing lwgeom on macOS

2018-02-25 Thread Kent Johnson
I am trying to install lwgeom 0.1-4 from source on macOS 10.13.3.

First try:
R CMD INSTALL lwgeom_0.1-4.tar.gz
...
checking for geos-config... no
no
configure: error: geos-config not found or not executable.

Second try:
R CMD INSTALL lwgeom_0.1-4.tar.gz
--configure-args='-with-geos-config=/Library/Frameworks/GEOS.framework/Versions/3/unix/bin/geos-config'
...
configure: geos-config set to
/Library/Frameworks/GEOS.framework/Versions/3/unix/bin/geos-config
checking geos-config exists... yes
checking geos-config executable... yes
checking geos-config usability... yes
configure: GEOS: 3.6.1
checking GEOS version >= 3.3.0... yes
checking geos_c.h usability... no
checking geos_c.h presence... no
checking for geos_c.h... no
configure: error: geos_c.h not found in given locations.

I do have liblwgeom installed as part of Postgres.app. I have tried adding
--with-liblwgeom=/Applications/Postgres.app/Contents/Versions/10/lib/liblwgeom-2.4.0.dylib
to --configure-args with the same failure.

I have the framework version of GEOS installed from kyngchaos and tried
adding
--configure-vars='CPPFLAGS=-I/Library/Frameworks/GEOS.framework/Versions/3/Headers'
with the same failure.

I don't really know what I'm doing here so any help is appreciated. FWIW
I'm installing lwgeom to get access to the st_make_valid() function.

Thank you!
Kent Johnson

[[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] help needed regarding package OSRM

2017-11-08 Thread Timothée Giraud

Hi,

osrmRoute() requests a route between 2 points, it can return a 
SpatialLinesDataFrame of the route with travel time (minutes) and travel 
distance (kilometers) in its data slot.


osrmTable() requests a travel time matrix between a set of points, it 
can return a matrix in minutes between sources and destinations.


The OSRM server cannot return a travel distance matrix (in km).

Thus, the only solution I see for now is to use a loop (or apply or 
whatever) with osrmRoute() :


devtools::install_github("rCarto/osrm")

library(osrm)
data("com")
mat <- data.frame(i = character(), j = character (),
  time = numeric(), distance = numeric(),
  stringsAsFactors = F)
k = 1
for (i in 1:2){
  for (j in 6:8){
    rout <- osrmRoute(src = com[i, c("comm_id", "lon","lat")],
  dst = com[j, c("comm_id", "lon","lat")], sp = T)
    mat[k, ] <- as.vector(rout@data[1,])
    k <- k + 1
    Sys.sleep(0.5)
  }
}
mat

Note that I use the github version of the package. This version is 
adapted to last changes made on the demo server.


Note also that I use a Sys.sleep(0.5)instruction in the loop to be 
gentle with the public OSRM demo server.


If you use your own OSRM server, the CRAN version will work and the 
Sys.sleep() instruction is useless.



Timothée Giraud

___
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 needed regarding package OSRM

2017-11-07 Thread Bacou, Melanie

  
  
This works for me (`f` is a data.frame of X,Y origin locations,
  `t` is a data.frame of X,Y destinations):
osrm_api <- function(f, t, key=NULL) {
  
    url <-
"https://router.project-osrm.org/table/v1/driving/"
    url <- paste0(url,
      paste(f$X, f$Y, sep=",", collapse=";"), ";",
paste(t$X, t$Y, sep=",", collapse=";"))
    out <- GET(url,
      query=list(
    sources=paste(1:nrow(f)-1, collapse=";"),
    destinations=paste(nrow(f):(nrow(f)+nrow(t)-1),
collapse=";")))
    out <- try(fromJSON(content(out, as="text"),
flatten=TRUE))
  return(out)
  
}


On 11/07/2017 08:27 AM, Shruti Tripathi
  wrote:


  Hi,

We want to compute the distances between two matrices of  points in (long,
lat)
This is how, as per the manual distance is calculated between two points:

route <- osrmRoute(src = "" c("comm_id", "lon","lat")],
dst = com[15, c("comm_id", "lon","lat")])

How would I compute the same for a matrix of source and destination, for
example

route <- osrmRoute(src = "" c("comm_id", "lon","lat")],
dst = com[11:20, c("comm_id", "lon","lat")])

how do i do this???

Regards
Shruti

	[[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

[R-sig-Geo] help needed regarding package OSRM

2017-11-07 Thread Shruti Tripathi
Hi,

We want to compute the distances between two matrices of  points in (long,
lat)
This is how, as per the manual distance is calculated between two points:

route <- osrmRoute(src = com[1, c("comm_id", "lon","lat")],
dst = com[15, c("comm_id", "lon","lat")])

How would I compute the same for a matrix of source and destination, for
example

route <- osrmRoute(src = com[1:10, c("comm_id", "lon","lat")],
dst = com[11:20, c("comm_id", "lon","lat")])

how do i do this???

Regards
Shruti

[[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] Help to interpret optimal bandwidth in ggwr.sel (spgwr package)

2017-10-14 Thread Manuel Ribeiro
Dear list, i am using spgwr as an exploratory tool in the analysis of
environment-health associations.

The study area is square, with dimensions 100x100 m.

 

In one of the results of my analysis, i found an optimal bandwidth
(optimizing the CV score) of 507 m.

And I interpret this bandwidth as a buffer distance where CV is the
smallest.

However, maximum (Euclidean) distance between any 2 points in the grid
(100x100) is 141,42 m, so I would expect an optimal bandwidth varying
between zero and 141 m. I am missing something in the interpretation of this
result, since the optimal bandwidth is 507 m.

If anyone can help me interpreting this correctly I will be deeply
appreciated

Kind regards

Manuel

 

Manuel C Ribeiro

Cerena - Centro de Recursos Naturais e Ambiente
Instituto Superior T�cnico
Av. Rovisco Pais  1049-001 Lisboa Portugal
Tel:  (+351) 21 841 74 41
Fax: (+351) 21 841 73 89

 


[[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 with plotKML::kml()

2017-08-07 Thread Tomislav Hengl


I think I set the color of the polygon line "white" which is the KML 
default, so you can only change the color of polygons (fill); see:


https://github.com/cran/plotKML/blob/master/R/layer.SpatialPolygons.R#L112

To change colors per polygon you should run:

data(eberg_zones)
legend = get("colour_scale_factor", envir = plotKML.opts)
kml_open("eberg_zones.kml")
kml_layer(eberg_zones, colour=ZONES, colour_scale=legend)
kml_close("eberg_zones.kml")

See also: http://gsif.isric.org/doku.php/wiki:tutorial_plotkml

Polygon outlines 
(https://developers.google.com/kml/documentation/kmlreference#polystyle) 
could also be changed but not via plotKML.


HTH,


On 07-08-17 17:46, MacQueen, Don wrote:

Hi Tomislav,

I am using the kml() function in the plotKML package to write a 
SpatialPolygonsDataFrame object to a kml file, and would like to know if it is 
possible to specify the fill color and border color separately. I have been 
looking at documentation and been unable to find a way. I would appreciate any 
suggestions.


Suppose "foo" is a SpatialPolygonsDataFrame object with a lat/long coordinate 
reference system. Then in R I can do, for example,

   plot(foo, col='yellow', border='red', lwd=2)

I would like to write a KML file that will display the polygon in Google Earth 
in a similar manner.

I have found that
plotKML::kml(foo, colour='yellow')
controls the fill color, but I can't find how to set the border color.

Ideally, I'd also like to be able specify border only, no fill, and also line 
widths for the border.

For example, the kml file might have in it something like:

 
 4DFF
 1
 1
 
 
 
 2
 



Thanks
-Don



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


[R-sig-Geo] Help with plotKML::kml() ?

2017-08-04 Thread MacQueen, Don
Can I get some help with the
   plotKML::kml()
function? I'm looking at various documentation and having trouble finding what 
I need.

Suppose "foo" is a SpatialPolygonsDataFrame object with a lat/long coordinate 
reference system. Then in R I can do, for example,

  plot(foo, col='yellow', border='red')

I want to write a KML file that will display the polygon in Google Earth with 
the same colors.

  plotKML::kml(foo, colour='yellow')

gets the fill, but I can't find how to set the border color.

I'd also like to be able to specify no fill, border only.

Thanks
-Don

-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062


___
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 for STFDF Object Creation

2017-04-23 Thread Ankur Sarker via R-sig-Geo
Thanks for your reply. Sorry for my second post, I tried to be more clear.

Here is link of my complete source code, data and R 
instance:https://drive.google.com/drive/folders/0B3tdiSZ9hBj4dVZXOXItUjdrRlE?usp=sharing


Hope, it would be easier to understand my problem. 

On Sunday, April 23, 2017 5:25 PM, Edzer Pebesma 
 wrote:
 

 Please provide a script of an example that we can reproduce, preferably
using data that is loaded from a package (to safe other people's time),
otherwise it is impossible for anyone to help you, or unlikely somebody
will. Your script does not create count data but assumes it is there;
you don't show which package you loaded; it is unclear what your problem is.

Your second post on this list came through completely scrambled, and
within 24 hours. Don't expect that reposting, or scrambling, helps.

On 23/04/17 06:02, Ankur Sarker via R-sig-Geo wrote:
> Hi,
> I am trying to create a STFDF object and draw variogram. However, I am 
> getting several errors. Here is my r code:
> #create count data
> c0157ts <- as.numeric(c(t(c0157)))
> c0001ts <- as.numeric(c(t(c0001)))
> 
> #create coordinates
>  lat <- 0
>  lon <- 0
>  lat[1] <- 34.0793684
>  lon[1] <- -81.1301722
>  lat[2] <- 33.979127
>  lon[2] <- -81.321166398
>  sp <- data.frame(lat,lon)
>  coordinates(sp)=~lon+lat
>  projection(sp)=CRS("+init=epsg:4326")
> 
> #create time object
> time_index <- seq(from = as.POSIXct("2017-01-02 01:00", tz = 'UTC'), to = 
> as.POSIXct("2017-03-22 00:00", tz = 'UTC'), by = "hour")
> 
> #combine the data
> mydata <- data.frame("count"=c(c0157ts,c0001ts)) 
> 
> #create STFDF object
> stfdf = STFDF(ozoneSP, time_index, mydata)
> #trying to create variogram
>    var <- 
>variogramST(count~1,data=stfdf,tunit="hours",assumeRegular=F,na.omit=T)which 
>gives me following error:0%Error in apply(do.call(cbind, lapply(ret, 
>function(x) x$np)), 1, sum,  : 
>      dim(X) must have a positive length
> I guess my STFDF object creation is not correct. Can anyone give us any hint? 
> Which elements in STFDF object is not correct.Here is the description of 
> STFDF object:> str(stfdf)
> Formal class 'STFDF' [package "spacetime"] with 4 slots
>  ..@ data  :'data.frame':    3792 obs. of  1 variable:
>  .. ..$ count: num [1:3792] 40 32 64 40 55 89 71 43 69 44 ...
>  ..@ sp    :Formal class 'SpatialPoints' [package "sp"] with 3 slots
>  .. .. ..@ coords    : num [1:2, 1:2] -9031369 -9052631 4015522 4002120
>  .. .. .. ..- attr(*, "dimnames")=List of 2
>  .. .. .. .. ..$ : NULL
>  .. .. .. .. ..$ : chr [1:2] "lon" "lat"
>  .. .. ..@ bbox      : num [1:2, 1:2] -9052631 4002120 -9031369 4015522
>  .. .. .. ..- attr(*, "dimnames")=List of 2
>  .. .. .. .. ..$ : chr [1:2] "lon" "lat"
>  .. .. .. .. ..$ : chr [1:2] "min" "max"
>  .. .. ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
>  .. .. .. .. ..@ projargs: chr "+init=epsg:3395 +proj=merc +lon_0=0 +k=1 
>+x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
>  ..@ time  :An ‘xts’ object on 2017-01-02 01:00:00/2017-03-22 containing:
>  Data: int [1:1896, 1] 1 2 3 4 5 6 7 8 9 10 ...
>  - attr(*, "dimnames")=List of 2
>  ..$ : NULL
>  ..$ : chr "timeIndex"
>  Indexed by objects of class: [POSIXct,POSIXt] TZ: UTC
>  xts Attributes:  
>  NULL
> Thanks for your help!
> With Regards,Rukna
>     [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

-- 
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/
___
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] Help for STFDF Object Creation

2017-04-23 Thread Edzer Pebesma
Please provide a script of an example that we can reproduce, preferably
using data that is loaded from a package (to safe other people's time),
otherwise it is impossible for anyone to help you, or unlikely somebody
will. Your script does not create count data but assumes it is there;
you don't show which package you loaded; it is unclear what your problem is.

Your second post on this list came through completely scrambled, and
within 24 hours. Don't expect that reposting, or scrambling, helps.

On 23/04/17 06:02, Ankur Sarker via R-sig-Geo wrote:
> Hi,
> I am trying to create a STFDF object and draw variogram. However, I am 
> getting several errors. Here is my r code:
> #create count data
> c0157ts <- as.numeric(c(t(c0157)))
> c0001ts <- as.numeric(c(t(c0001)))
> 
> #create coordinates
>   lat <- 0
>   lon <- 0
>   lat[1] <- 34.0793684
>   lon[1] <- -81.1301722
>   lat[2] <- 33.979127
>   lon[2] <- -81.321166398
>   sp <- data.frame(lat,lon)
>   coordinates(sp)=~lon+lat
>   projection(sp)=CRS("+init=epsg:4326")
> 
> #create time object
> time_index <- seq(from = as.POSIXct("2017-01-02 01:00", tz = 'UTC'), to = 
> as.POSIXct("2017-03-22 00:00", tz = 'UTC'), by = "hour")
> 
> #combine the data
> mydata <- data.frame("count"=c(c0157ts,c0001ts)) 
> 
> #create STFDF object
> stfdf = STFDF(ozoneSP, time_index, mydata)
> #trying to create variogram
> var <- 
> variogramST(count~1,data=stfdf,tunit="hours",assumeRegular=F,na.omit=T)which 
> gives me following error:0%Error in apply(do.call(cbind, lapply(ret, 
> function(x) x$np)), 1, sum,  : 
>   dim(X) must have a positive length
> I guess my STFDF object creation is not correct. Can anyone give us any hint? 
> Which elements in STFDF object is not correct.Here is the description of 
> STFDF object:> str(stfdf)
> Formal class 'STFDF' [package "spacetime"] with 4 slots
>   ..@ data   :'data.frame': 3792 obs. of  1 variable:
>   .. ..$ count: num [1:3792] 40 32 64 40 55 89 71 43 69 44 ...
>   ..@ sp :Formal class 'SpatialPoints' [package "sp"] with 3 slots
>   .. .. ..@ coords : num [1:2, 1:2] -9031369 -9052631 4015522 4002120
>   .. .. .. ..- attr(*, "dimnames")=List of 2
>   .. .. .. .. ..$ : NULL
>   .. .. .. .. ..$ : chr [1:2] "lon" "lat"
>   .. .. ..@ bbox   : num [1:2, 1:2] -9052631 4002120 -9031369 4015522
>   .. .. .. ..- attr(*, "dimnames")=List of 2
>   .. .. .. .. ..$ : chr [1:2] "lon" "lat"
>   .. .. .. .. ..$ : chr [1:2] "min" "max"
>   .. .. ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
>   .. .. .. .. ..@ projargs: chr "+init=epsg:3395 +proj=merc +lon_0=0 +k=1 
> +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
>   ..@ time   :An ‘xts’ object on 2017-01-02 01:00:00/2017-03-22 containing:
>   Data: int [1:1896, 1] 1 2 3 4 5 6 7 8 9 10 ...
>  - attr(*, "dimnames")=List of 2
>   ..$ : NULL
>   ..$ : chr "timeIndex"
>   Indexed by objects of class: [POSIXct,POSIXt] TZ: UTC
>   xts Attributes:  
>  NULL
> Thanks for your help!
> With Regards,Rukna
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

-- 
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/



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

[R-sig-Geo] Help for STFDF Object Creation

2017-04-22 Thread Ankur Sarker via R-sig-Geo
Hi,
I am trying to create a STFDF object and draw variogram. However, I am getting 
several errors. Here is my r code:
#create count data
c0157ts <- as.numeric(c(t(c0157)))
c0001ts <- as.numeric(c(t(c0001)))

#create coordinates
  lat <- 0
  lon <- 0
  lat[1] <- 34.0793684
  lon[1] <- -81.1301722
  lat[2] <- 33.979127
  lon[2] <- -81.321166398
  sp <- data.frame(lat,lon)
  coordinates(sp)=~lon+lat
  projection(sp)=CRS("+init=epsg:4326")

#create time object
time_index <- seq(from = as.POSIXct("2017-01-02 01:00", tz = 'UTC'), to = 
as.POSIXct("2017-03-22 00:00", tz = 'UTC'), by = "hour")

#combine the data
mydata <- data.frame("count"=c(c0157ts,c0001ts)) 

#create STFDF object
stfdf = STFDF(ozoneSP, time_index, mydata)
#trying to create variogram
var <- 
variogramST(count~1,data=stfdf,tunit="hours",assumeRegular=F,na.omit=T)which 
gives me following error:0%Error in apply(do.call(cbind, lapply(ret, 
function(x) x$np)), 1, sum,  : 
  dim(X) must have a positive length
I guess my STFDF object creation is not correct. Can anyone give us any hint? 
Which elements in STFDF object is not correct.Here is the description of STFDF 
object:> str(stfdf)
Formal class 'STFDF' [package "spacetime"] with 4 slots
  ..@ data   :'data.frame': 3792 obs. of  1 variable:
  .. ..$ count: num [1:3792] 40 32 64 40 55 89 71 43 69 44 ...
  ..@ sp :Formal class 'SpatialPoints' [package "sp"] with 3 slots
  .. .. ..@ coords : num [1:2, 1:2] -9031369 -9052631 4015522 4002120
  .. .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. .. ..$ : NULL
  .. .. .. .. ..$ : chr [1:2] "lon" "lat"
  .. .. ..@ bbox   : num [1:2, 1:2] -9052631 4002120 -9031369 4015522
  .. .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. .. ..$ : chr [1:2] "lon" "lat"
  .. .. .. .. ..$ : chr [1:2] "min" "max"
  .. .. ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
  .. .. .. .. ..@ projargs: chr "+init=epsg:3395 +proj=merc +lon_0=0 +k=1 
+x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
  ..@ time   :An ‘xts’ object on 2017-01-02 01:00:00/2017-03-22 containing:
  Data: int [1:1896, 1] 1 2 3 4 5 6 7 8 9 10 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "timeIndex"
  Indexed by objects of class: [POSIXct,POSIXt] TZ: UTC
  xts Attributes:  
 NULL
Thanks for your help!
With Regards,Rukna
[[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: Fitting a model variogram

2017-02-08 Thread Kapo Coulibaly
Can you share your variogram (a graph) and your initial parameters?

On Wed, Feb 8, 2017 at 1:55 AM, Kareem Longwe 
wrote:

> Dear all
> I am trying to fit a model variogram, but I am stuck on *ini.cov.pars. *I
> am working in R.
>
> Would anyone give me a clue how to estimate the 'partial sill and range'. I
> have tried changing numbers but I continuously get the following error
> message in R:
>
>  Warning messages:
> 1: In variofit(vario.pht, cov.model = "exponential", ini.cov.pars =
> initial.values,  :
>   unreasonable initial value for sigmasq (too high)
> 2: In variofit(vario.pht, cov.model = "exponential", ini.cov.pars =
> initial.values,  :
>   unreasonable initial value for sigmasq + nugget (too high).
>
> Thanks
>
> *Kareem Longwe*
> *NEPADSAN*Bio Student Ambassador
> MSc Student, Agronomy
> Lilongwe University of Agriculture and Natural Resources
> P.O. Box 219.
>
> klon...@bunda.luanar.mw
> +265 996 31 66 22
>
> [[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


[R-sig-Geo] HELP: Fitting a model variogram

2017-02-08 Thread Kareem Longwe
Dear all
I am trying to fit a model variogram, but I am stuck on *ini.cov.pars. *I
am working in R.

Would anyone give me a clue how to estimate the 'partial sill and range'. I
have tried changing numbers but I continuously get the following error
message in R:

 Warning messages:
1: In variofit(vario.pht, cov.model = "exponential", ini.cov.pars =
initial.values,  :
  unreasonable initial value for sigmasq (too high)
2: In variofit(vario.pht, cov.model = "exponential", ini.cov.pars =
initial.values,  :
  unreasonable initial value for sigmasq + nugget (too high).

Thanks

*Kareem Longwe*
*NEPADSAN*Bio Student Ambassador
MSc Student, Agronomy
Lilongwe University of Agriculture and Natural Resources
P.O. Box 219.

klon...@bunda.luanar.mw
+265 996 31 66 22

[[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 regarding Autoencoder

2017-01-24 Thread Roger Bivand

On Tue, 24 Jan 2017, Subir Paul wrote:


Dear All,
I was using "SAENET" package for autoencoding.
I used the following code:
h=SAENET.train(data[,1:200], n.nodes = c(100, 20), unit.type =
("logistic"), lambda = 0.001,
  beta = 0.0001, rho = 0.01, epsilon = 0.01, optim.method =
c("BFGS"),
  rel.tol=sqrt(.Machine$double.eps), max.iterations = 1000)
But its showing the error:
Error in optim(par = theta, fn = J.theta, gr = grad.theta.J, method =
optimizer,  :
 initial value in 'vmmin' is not finite

Can anyone help me regarding this issue?


Try saying debug(SAENET.train) and stepping through to see what initial 
value is being passed to optim for vmmin. It may be an issue with your 
input data, or it may be something in the function that makes unmet 
assumptions about your data. Running traceback() after such an error 
probably will only show that optim is being passed a a non-finite value 
(divide by zero, log of zero?). Consider asking the package maintainer, 
and if possible provide a small, reproducible example.


Hope this helps,

Roger



Thanks in advance.

*With Regards*
*Subir Paul*
*Research Scholar (PhD)*
*Water Resources & Env. Engg.*

*Department of Civil Engineering*
*Indian Institute of Science, Bengaluru*

[[alternative HTML version deleted]]

___
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
http://orcid.org/-0003-2392-6140
https://scholar.google.no/citations?user=AWeghB0J=en
http://depsy.org/person/434412

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


[R-sig-Geo] Help regarding Autoencoder

2017-01-24 Thread Subir Paul
Dear All,
I was using "SAENET" package for autoencoding.
I used the following code:
h=SAENET.train(data[,1:200], n.nodes = c(100, 20), unit.type =
("logistic"), lambda = 0.001,
   beta = 0.0001, rho = 0.01, epsilon = 0.01, optim.method =
c("BFGS"),
   rel.tol=sqrt(.Machine$double.eps), max.iterations = 1000)
But its showing the error:
Error in optim(par = theta, fn = J.theta, gr = grad.theta.J, method =
optimizer,  :
  initial value in 'vmmin' is not finite

Can anyone help me regarding this issue?

Thanks in advance.

*With Regards*
*Subir Paul*
*Research Scholar (PhD)*
*Water Resources & Env. Engg.*

*Department of Civil Engineering*
*Indian Institute of Science, Bengaluru*

[[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: impact measures in spatial panel durbin model

2016-04-20 Thread Youba Ndiaye
  Thanks a lot. That's very helpful

Best regards.
Youba.

Roger Bivand  a écrit :

> On Wed, 20 Apr 2016, Youba Ndiaye wrote:
>
>> Dear all,
>>
>> I'm a Ph.D student  and I'm working on spatial econometrics approach.
>>
>> I want to implement a static spatial durbin model  in R  with "splm"
>> function. But the particular case of my model is that my durbin model is
>> partial such as:  
>> y = rho.Wy + X.beta + WZ.theta + epsilon   
>>
>> X and Z are vectors of explanatory variables with respectively (N,k)
and
>> (N, m) dimensions. k>m. In orders words, the Z is a spatially lagged
>> subset
>> of X.
>>
>> My aim is to calculate properly impact measures of this model in R.
>
> All of the impacts methods expect k=m. A sketch of a possible approach
is:
>
> library(spdep)
> example(columbus)
> lw <- nb2listw(col.gal.nb)
> f <- CRIME ~ INC + HOVAL + I(lag(lw, HOVAL))
> mod <- lagsarlm(f, data=columbus, lw)
> summary(mod)
>
> by constructing the (dense) S(W)_r matrices differently for the
> non-Durbin and Durbin variables:
>
> iIrW <- invIrW(lw, mod$rho)
> S_INC <- iIrW %*% (mod$coefficients[2]*diag(nrow(columbus)))
> S_HOVAL <- iIrW %*% ((mod$coefficients[3]*diag(nrow(columbus))) -
> (mod$coefficients[4]*listw2mat(lw)))
>
> Then you can get the direct and total impacts in the usual way:
>
> dir_INC <- sum(diag(S_INC))/nrow(columbus)
> dir_HOVAL <- sum(diag(S_HOVAL))/nrow(columbus)
> tot_INC <- sum(c(S_INC))/nrow(columbus)
> tot_HOVAL <- sum(c(S_HOVAL))/nrow(columbus)
>
> with indir_* = tot_* - dir_*.
>
> No inference tools are available, though.
>
> It might be possible to inject zero WZ coefficient values and
> covariances for non-included WX variables in order to use the standard
> impacts methods, but you need strong reasons apriori to assume that they
> are zero; going with regular Durbin will be likely to be more robust,
> and will give a clear test of the insignificance of the indirect impacts.
>
> Hope this helps,
>
> Roger
>
>> Thank You in advance.
>> Best regards.
>> Youba.
>>
>>         [[alternative HTML version deleted]]
>>
>> ___
>> 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; fax +47 55 95 91 00
> e-mail: roger.biv...@nhh.no
> http://orcid.org/-0003-2392-6140
>
https://scholar.google.no/citations?user=AWeghB0J=enhttp://depsy.org/person/434412

[[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: impact measures in spatial panel durbin model

2016-04-20 Thread Roger Bivand

On Wed, 20 Apr 2016, Youba Ndiaye wrote:


Dear all,

I'm a Ph.D student  and I'm working on spatial econometrics approach.

I want to implement a static spatial durbin model  in R  with "splm"
function. But the particular case of my model is that my durbin model is
partial such as:  
y = rho.Wy + X.beta + WZ.theta + epsilon   

X and Z are vectors of explanatory variables with respectively (N,k) and
(N, m) dimensions. k>m. In orders words, the Z is a spatially lagged subset
of X.

My aim is to calculate properly impact measures of this model in R.


All of the impacts methods expect k=m. A sketch of a possible approach is:

library(spdep)
example(columbus)
lw <- nb2listw(col.gal.nb)
f <- CRIME ~ INC + HOVAL + I(lag(lw, HOVAL))
mod <- lagsarlm(f, data=columbus, lw)
summary(mod)

by constructing the (dense) S(W)_r matrices differently for the non-Durbin 
and Durbin variables:


iIrW <- invIrW(lw, mod$rho)
S_INC <- iIrW %*% (mod$coefficients[2]*diag(nrow(columbus)))
S_HOVAL <- iIrW %*% ((mod$coefficients[3]*diag(nrow(columbus))) -
  (mod$coefficients[4]*listw2mat(lw)))

Then you can get the direct and total impacts in the usual way:

dir_INC <- sum(diag(S_INC))/nrow(columbus)
dir_HOVAL <- sum(diag(S_HOVAL))/nrow(columbus)
tot_INC <- sum(c(S_INC))/nrow(columbus)
tot_HOVAL <- sum(c(S_HOVAL))/nrow(columbus)

with indir_* = tot_* - dir_*.

No inference tools are available, though.

It might be possible to inject zero WZ coefficient values and covariances 
for non-included WX variables in order to use the standard impacts 
methods, but you need strong reasons apriori to assume that they are zero; 
going with regular Durbin will be likely to be more robust, and will give 
a clear test of the insignificance of the indirect impacts.


Hope this helps,

Roger



Thank You in advance.
Best regards.
Youba.

[[alternative HTML version deleted]]

___
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; fax +47 55 95 91 00
e-mail: roger.biv...@nhh.no
http://orcid.org/-0003-2392-6140
https://scholar.google.no/citations?user=AWeghB0J=en
http://depsy.org/person/434412___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo

[R-sig-Geo] Help: impact measures in spatial panel durbin model

2016-04-20 Thread Youba Ndiaye
Dear all,

I'm a Ph.D student  and I'm working on spatial econometrics approach.

I want to implement a static spatial durbin model  in R  with "splm"
function. But the particular case of my model is that my durbin model is
partial such as:  
y = rho.Wy + X.beta + WZ.theta + epsilon   

X and Z are vectors of explanatory variables with respectively (N,k) and
(N, m) dimensions. k>m. In orders words, the Z is a spatially lagged subset
of X.

My aim is to calculate properly impact measures of this model in R.

Thank You in advance.
Best regards.
Youba.

[[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 with 2d- Density plots (ggplot2)

2016-01-16 Thread Thierry Onkelinx
Dear Amao,

It's not clear how the "hundreds of species" come into the play. Do you
want a map for each species? Or rather a single map that combines the
species info.

ggplot2() has AFAIK no options to restrict the output of stat_bin2d() to a
polygon.

Best regards,


ir. Thierry Onkelinx
Instituut voor natuur- en bosonderzoek / Research Institute for Nature and
Forest
team Biometrie & Kwaliteitszorg / team Biometrics & Quality Assurance
Kliniekstraat 25
1070 Anderlecht
Belgium

To call in the statistician after the experiment is done may be no more
than asking him to perform a post-mortem examination: he may be able to say
what the experiment died of. ~ Sir Ronald Aylmer Fisher
The plural of anecdote is not data. ~ Roger Brinner
The combination of some data and an aching desire for an answer does not
ensure that a reasonable answer can be extracted from a given body of data.
~ John Tukey

2016-01-15 18:00 GMT+01:00 Amao Abduljamiu :

> Dear All,
>
> I need help with 2d- Density plots (ggplot2)...
>
> I'm trying to plot ecological distribution of some species of organisms i'm
> studying over the Arabian/Persian Gulf. Here is a sample of code i've
> tried,
>
> Backround layer
>
> nc <- get_map("Persian Gulf", zoom = 6, maptype = 'terrain', language =
> "English")
> ncmap <- ggmap(nc,  extent = "device")
>
> Other layers
>
>   ncmap+
> stat_density2d(data=sample.data3, aes(x=long, y=lat, fill=..level..,
> alpha=..level..),geom="polygon")+
> geom_point(data=sample.data3, aes(x=long, y=lat))+
> geom_point(aes(x =50.626444, y = 26.044472), color="red", size = 4)+
> scale_fill_gradient(low = "green", high = "red") + scale_alpha(range =
> c(0.00, 0.25), guide = FALSE)
>
> but , i will like to use the stat_density2d to show the distributions of
> hundreds of species (which are recorded in columns e.g SP1SPn) over the
> water body rather than just displaying latitude and longitude.
>
> Also, is it possible to restrict my heat map to just the water body ? I'll
> appreciate any help and recommendations i can get on this please
>
> I will also appreciate any suggestion on alternative way to achieve this.
>
>
> Here is a link to stackoverflow where I initially asked the question with
> an
> image of what the problem look like.
>
>
> http://stackoverflow.com/questions/34569152/ggplot-stat-density2d-plots-for-
> ecological-distribution
>
> Sincerely
> Amao
> ---
> Amao Abduljamiu O.
> PhD Candidate - Geology
> Earth Sciences Department
> King Fahd University of Petroleum and Minerals (KFUPM)
> Dhahran, Saudi Arabia
> P. O. Box 1723 KFUPM, Dhahran 31261 Saudi Arabia
> Tel. office +966 3 860 3240
> Mobile: +966 535467527
> Skype: lakesido02
> Email: a...@kfupm.edu.sa
> Alt: lekis...@gmail.com
>
> ___
> 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] help with 2d- Density plots (ggplot2)

2016-01-16 Thread Amao Abduljamiu
Yes Sir, my plan is to have several maps .i.e a map for each species. 

Sent from my iPad

> On Jan 16, 2016, at 10:18 PM, Thierry Onkelinx  
> wrote:
> 
> Dear Amao,
> 
> It's not clear how the "hundreds of species" come into the play. Do you want 
> a map for each species? Or rather a single map that combines the species info.
> 
> ggplot2() has AFAIK no options to restrict the output of stat_bin2d() to a 
> polygon. 
> 
> Best regards,
> 
> 
> ir. Thierry Onkelinx
> Instituut voor natuur- en bosonderzoek / Research Institute for Nature and 
> Forest 
> team Biometrie & Kwaliteitszorg / team Biometrics & Quality Assurance 
> Kliniekstraat 25
> 1070 Anderlecht
> Belgium
> 
> To call in the statistician after the experiment is done may be no more than 
> asking him to perform a post-mortem examination: he may be able to say what 
> the experiment died of. ~ Sir Ronald Aylmer Fisher
> The plural of anecdote is not data. ~ Roger Brinner 
> The combination of some data and an aching desire for an answer does not 
> ensure that a reasonable answer can be extracted from a given body of data. ~ 
> John Tukey
> 
> 2016-01-15 18:00 GMT+01:00 Amao Abduljamiu :
>> Dear All,
>> 
>> I need help with 2d- Density plots (ggplot2)...
>> 
>> I'm trying to plot ecological distribution of some species of organisms i'm
>> studying over the Arabian/Persian Gulf. Here is a sample of code i've tried,
>> 
>> Backround layer
>> 
>> nc <- get_map("Persian Gulf", zoom = 6, maptype = 'terrain', language =
>> "English")
>> ncmap <- ggmap(nc,  extent = "device")
>> 
>> Other layers
>> 
>>   ncmap+
>> stat_density2d(data=sample.data3, aes(x=long, y=lat, fill=..level..,
>> alpha=..level..),geom="polygon")+
>> geom_point(data=sample.data3, aes(x=long, y=lat))+
>> geom_point(aes(x =50.626444, y = 26.044472), color="red", size = 4)+
>> scale_fill_gradient(low = "green", high = "red") + scale_alpha(range =
>> c(0.00, 0.25), guide = FALSE)
>> 
>> but , i will like to use the stat_density2d to show the distributions of
>> hundreds of species (which are recorded in columns e.g SP1SPn) over the
>> water body rather than just displaying latitude and longitude.
>> 
>> Also, is it possible to restrict my heat map to just the water body ? I'll
>> appreciate any help and recommendations i can get on this please
>> 
>> I will also appreciate any suggestion on alternative way to achieve this.
>> 
>> 
>> Here is a link to stackoverflow where I initially asked the question with an
>> image of what the problem look like.
>> 
>> http://stackoverflow.com/questions/34569152/ggplot-stat-density2d-plots-for-
>> ecological-distribution
>> 
>> Sincerely
>> Amao
>> ---
>> Amao Abduljamiu O.
>> PhD Candidate - Geology
>> Earth Sciences Department
>> King Fahd University of Petroleum and Minerals (KFUPM)
>> Dhahran, Saudi Arabia
>> P. O. Box 1723 KFUPM, Dhahran 31261 Saudi Arabia
>> Tel. office +966 3 860 3240
>> Mobile: +966 535467527
>> Skype: lakesido02
>> Email: a...@kfupm.edu.sa
>> Alt: lekis...@gmail.com
>> 
>> ___
>> 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


[R-sig-Geo] help with 2d- Density plots (ggplot2)

2016-01-15 Thread Amao Abduljamiu
Dear All, 

I need help with 2d- Density plots (ggplot2)...

I'm trying to plot ecological distribution of some species of organisms i'm
studying over the Arabian/Persian Gulf. Here is a sample of code i've tried,

Backround layer

nc <- get_map("Persian Gulf", zoom = 6, maptype = 'terrain', language =
"English")
ncmap <- ggmap(nc,  extent = "device")

Other layers

  ncmap+
stat_density2d(data=sample.data3, aes(x=long, y=lat, fill=..level..,
alpha=..level..),geom="polygon")+
geom_point(data=sample.data3, aes(x=long, y=lat))+
geom_point(aes(x =50.626444, y = 26.044472), color="red", size = 4)+
scale_fill_gradient(low = "green", high = "red") + scale_alpha(range =
c(0.00, 0.25), guide = FALSE)

but , i will like to use the stat_density2d to show the distributions of
hundreds of species (which are recorded in columns e.g SP1SPn) over the
water body rather than just displaying latitude and longitude.

Also, is it possible to restrict my heat map to just the water body ? I'll
appreciate any help and recommendations i can get on this please

I will also appreciate any suggestion on alternative way to achieve this.


Here is a link to stackoverflow where I initially asked the question with an
image of what the problem look like. 

http://stackoverflow.com/questions/34569152/ggplot-stat-density2d-plots-for-
ecological-distribution

Sincerely
Amao
---
Amao Abduljamiu O.
PhD Candidate - Geology
Earth Sciences Department
King Fahd University of Petroleum and Minerals (KFUPM)
Dhahran, Saudi Arabia
P. O. Box 1723 KFUPM, Dhahran 31261 Saudi Arabia
Tel. office +966 3 860 3240
Mobile: +966 535467527
Skype: lakesido02
Email: a...@kfupm.edu.sa
Alt: lekis...@gmail.com

___
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 with as.numeric(rownames(over(SpatialPoints(set1, set2, returnList= TRUE)[[1]]))

2015-11-02 Thread chris english
Hi Alan;
As you say, runs most of the time. I took the liberty of cleaning out the
>'s, removed the call to plyr as it doesn't seem to be used, and the
rm(list=ls()) since I wasn't playing in a sandbox. How frequently does it
misbehave?

I'm sorry I can't offer anything more constructive than the clean up.  I'm
interested in identifying self-avoiding random walks SAW which means I'll
first have to figure out how to implement one, then figure out how to test
for one. And means getting my head around your  "which_next <-
sample(c("bb","dd","ff","hh"),1)" logic.

Chris

## reproducible example code
 #rm(list = ls())
 library(deldir)
 library(sp)
 #library(plyr)
 side_length = 100
 ## Create random SET of XY coordinates (size = 100x100)
 set.seed(11)
 df = data.frame(matrix(sample(1:100,16,replace=TRUE),nrow=8))
 ## Convert df to SPatialPointsDataFrame
 spdf <- SpatialPointsDataFrame(df,df)
 ## deldir() function creates tesselation (voronoi) plot
 z <- deldir(df,plotit=TRUE,wl='te')
 ## tile.list() creates a list of data for tiles
 zz <- tile.list(deldir(df,plotit=TRUE,wl='te'))
 ## Voronoi Polygons Function
 voronoipolygons = function(layer) {
   require(deldir)
   crds = layer@coords
   z = deldir(crds[,1], crds[,2])
   w = tile.list(z)
   polys = vector(mode='list', length=length(w))
   require(sp)
   for (i in seq(along=polys)) {
 pcrds = cbind(w[[i]]$x, w[[i]]$y)
 pcrds = rbind(pcrds, pcrds[1,])
 polys[[i]] = Polygons(list(Polygon(pcrds)), ID=as.character(i))
   }
   SP = SpatialPolygons(polys)
   voronoi = SpatialPolygonsDataFrame(SP, data=data.frame(x=crds[,1],
 y=crds[,2], row.names=sapply(slot(SP, 'polygons'),
 function(x) slot(x, 'ID'
 }
 ## Generate SpatialPolygonsDataFrame to use as input for over() function
 vpl <- voronoipolygons(spdf)
 ## Random Walk Function generates North, South East or West movement
 ## with transit from across screen (like PacMan, going out one side,
 ## coming back on the other side) to prevent getting stuck in corner
 random_walk <- function(step_quantity, step_length, plot = FALSE){
   require(ggplot2)

   walker <- data.frame(matrix(c(0,0), nrow = step_quantity, ncol = 3,
 byrow = T))
   names(walker)[1]<-paste("x")
   names(walker)[2]<-paste("y")
   names(walker)[3]<-paste("which")

   ## Seed random initial starting point
   walker[1,1:2] <- matrix(sample(1:100,2,replace=TRUE),nrow=1)
   walker[1,3] <- as.numeric(rownames(over(SpatialPoints(walker[1,1:2]
),vpl,returnList=TRUE)[[1]]))

  where_to <- as.numeric()

   for(i in 2:step_quantity){
 where_to <- as.numeric()
 where_to <- walker[i-1,1:2]
 which_next <- sample(c("bb","dd","ff","hh"),1)

 if (which_next == "bb") {
   if (walker[i-1,2] == side_length) {where_to[1,2] <- 0
   } else {where_to[1,2] <- walker[i-1,2]+step_length}
 }

 else if (which_next == "dd") {
   if (walker[i-1,1] == 0 ) {where_to[1,1] <- side_length
   } else {where_to[1,1] <- walker[i-1,1]-step_length}
 }

else if (which_next == "ff") {
   if (walker[i-1,1] == side_length) {where_to[1,1] <- 0
   } else {where_to[1,1] <- walker[i-1,1]+step_length}
 }
 else {
   if (walker[i-1,2] == 0) {where_to[1,2] <- side_length
   } else {where_to[1,2] <- walker[i-1,2]-step_length}
 }

 walker[i,1:2] <- where_to
   }

   walker[i,3] <- as.numeric(rownames(over(SpatialPoints(walker[i,1:2]),
   vpl,returnList= TRUE)[[1]]))


   if(plot){
   require(ggplot2)
   p <- ggplot(walker, aes(x = x, y = y))
   p <- p + geom_path()
   print(p)
   }

   return(walker)
 }
 try(transits <- random_walk(5000,1),silent=F)

On Sun, Nov 1, 2015 at 1:35 PM, Alan Briggs  wrote:

> Hello.
>
> Below is a fully repeatable R-Script that I'm having trouble with.
> Generally, here's what I'm trying to do:
>
> 1) Randomly generate a tile.list()
> 2) Randomly generate a new point
> 3) Identify which polygon in the tile.list the new randomly generated point
> is in
>
> This works fine MOST of the time. However, occasionally, I get an error
> returned:
>
> Error in `[<-.data.frame`(`*tmp*`, list, 3, value = numeric(0)) :
> >   replacement has length zero
>
>
> While troubleshooting, I realized I get numeric(0) returned for certain
> sets of new random points when I run the command
> as.numeric(rownames(over(SpatialPoints(walker[i,1:2]),vpl,returnList=
> TRUE)[[1]])). I thought maybe this was a boundary issue, but the points
> don't lie on the edge, nor are they the centroid.
>
> Any help you can provide would be greatly appreciated!
>
> Regards,
>
> Alan
>
> R-Script Below:
>
> ### Help Question for  r-sig-geo ###
> > rm(list = ls())
> > library(deldir)
> > library(sp)
> > library(plyr)
> > side_length = 100
> > ## Create random SET of XY coordinates (size = 100x100)
> > set.seed(11)
> > df = data.frame(matrix(sample(1:100,16,replace=TRUE),nrow=8))
> > ## Convert df to SPatialPointsDataFrame
> > spdf <- 

Re: [R-sig-Geo] Help with as.numeric(rownames(over(SpatialPoints(set1, set2, returnList= TRUE)[[1]]))

2015-11-02 Thread chris english
Alan,

Possibly a nonsensical way of testing but I ran

rep(try(transits <- random_walk(5000,1),silent=F), 100)

and it completed without issue.

Chris

On Mon, Nov 2, 2015 at 5:33 AM, chris english  wrote:

> Hi Alan;
> As you say, runs most of the time. I took the liberty of cleaning out the
> >'s, removed the call to plyr as it doesn't seem to be used, and the
> rm(list=ls()) since I wasn't playing in a sandbox. How frequently does it
> misbehave?
>
> I'm sorry I can't offer anything more constructive than the clean up.  I'm
> interested in identifying self-avoiding random walks SAW which means I'll
> first have to figure out how to implement one, then figure out how to test
> for one. And means getting my head around your  "which_next <-
> sample(c("bb","dd","ff","hh"),1)" logic.
>
> Chris
>
> ## reproducible example code
>  #rm(list = ls())
>  library(deldir)
>  library(sp)
>  #library(plyr)
>  side_length = 100
>  ## Create random SET of XY coordinates (size = 100x100)
>  set.seed(11)
>  df = data.frame(matrix(sample(1:100,16,replace=TRUE),nrow=8))
>  ## Convert df to SPatialPointsDataFrame
>  spdf <- SpatialPointsDataFrame(df,df)
>  ## deldir() function creates tesselation (voronoi) plot
>  z <- deldir(df,plotit=TRUE,wl='te')
>  ## tile.list() creates a list of data for tiles
>  zz <- tile.list(deldir(df,plotit=TRUE,wl='te'))
>  ## Voronoi Polygons Function
>  voronoipolygons = function(layer) {
>require(deldir)
>crds = layer@coords
>z = deldir(crds[,1], crds[,2])
>w = tile.list(z)
>polys = vector(mode='list', length=length(w))
>require(sp)
>for (i in seq(along=polys)) {
>  pcrds = cbind(w[[i]]$x, w[[i]]$y)
>  pcrds = rbind(pcrds, pcrds[1,])
>  polys[[i]] = Polygons(list(Polygon(pcrds)), ID=as.character(i))
>}
>SP = SpatialPolygons(polys)
>voronoi = SpatialPolygonsDataFrame(SP, data=data.frame(x=crds[,1],
>  y=crds[,2], row.names=sapply(slot(SP, 'polygons'),
>  function(x) slot(x, 'ID'
>  }
>  ## Generate SpatialPolygonsDataFrame to use as input for over() function
>  vpl <- voronoipolygons(spdf)
>  ## Random Walk Function generates North, South East or West movement
>  ## with transit from across screen (like PacMan, going out one side,
>  ## coming back on the other side) to prevent getting stuck in corner
>  random_walk <- function(step_quantity, step_length, plot = FALSE){
>require(ggplot2)
>
>walker <- data.frame(matrix(c(0,0), nrow = step_quantity, ncol = 3,
>  byrow = T))
>names(walker)[1]<-paste("x")
>names(walker)[2]<-paste("y")
>names(walker)[3]<-paste("which")
>
>## Seed random initial starting point
>walker[1,1:2] <- matrix(sample(1:100,2,replace=TRUE),nrow=1)
>walker[1,3] <- as.numeric(rownames(over(SpatialPoints(walker[1,1:2]
> ),vpl,returnList=TRUE)[[1]]))
>
>   where_to <- as.numeric()
>
>for(i in 2:step_quantity){
>  where_to <- as.numeric()
>  where_to <- walker[i-1,1:2]
>  which_next <- sample(c("bb","dd","ff","hh"),1)
>
>  if (which_next == "bb") {
>if (walker[i-1,2] == side_length) {where_to[1,2] <- 0
>} else {where_to[1,2] <- walker[i-1,2]+step_length}
>  }
>
>  else if (which_next == "dd") {
>if (walker[i-1,1] == 0 ) {where_to[1,1] <- side_length
>} else {where_to[1,1] <- walker[i-1,1]-step_length}
>  }
>
> else if (which_next == "ff") {
>if (walker[i-1,1] == side_length) {where_to[1,1] <- 0
>} else {where_to[1,1] <- walker[i-1,1]+step_length}
>  }
>  else {
>if (walker[i-1,2] == 0) {where_to[1,2] <- side_length
>} else {where_to[1,2] <- walker[i-1,2]-step_length}
>  }
>
>  walker[i,1:2] <- where_to
>}
>
>walker[i,3] <- as.numeric(rownames(over(SpatialPoints(walker[i,1:2]),
>vpl,returnList= TRUE)[[1]]))
>
>
>if(plot){
>require(ggplot2)
>p <- ggplot(walker, aes(x = x, y = y))
>p <- p + geom_path()
>print(p)
>}
>
>return(walker)
>  }
>  try(transits <- random_walk(5000,1),silent=F)
>
> On Sun, Nov 1, 2015 at 1:35 PM, Alan Briggs  wrote:
>
>> Hello.
>>
>> Below is a fully repeatable R-Script that I'm having trouble with.
>> Generally, here's what I'm trying to do:
>>
>> 1) Randomly generate a tile.list()
>> 2) Randomly generate a new point
>> 3) Identify which polygon in the tile.list the new randomly generated
>> point
>> is in
>>
>> This works fine MOST of the time. However, occasionally, I get an error
>> returned:
>>
>> Error in `[<-.data.frame`(`*tmp*`, list, 3, value = numeric(0)) :
>> >   replacement has length zero
>>
>>
>> While troubleshooting, I realized I get numeric(0) returned for certain
>> sets of new random points when I run the command
>> as.numeric(rownames(over(SpatialPoints(walker[i,1:2]),vpl,returnList=
>> TRUE)[[1]])). I thought maybe this was a boundary issue, but the points
>> don't lie on the edge, 

[R-sig-Geo] Help with as.numeric(rownames(over(SpatialPoints(set1, set2, returnList= TRUE)[[1]]))

2015-11-01 Thread Alan Briggs
Hello.

Below is a fully repeatable R-Script that I'm having trouble with.
Generally, here's what I'm trying to do:

1) Randomly generate a tile.list()
2) Randomly generate a new point
3) Identify which polygon in the tile.list the new randomly generated point
is in

This works fine MOST of the time. However, occasionally, I get an error
returned:

Error in `[<-.data.frame`(`*tmp*`, list, 3, value = numeric(0)) :
>   replacement has length zero


While troubleshooting, I realized I get numeric(0) returned for certain
sets of new random points when I run the command
as.numeric(rownames(over(SpatialPoints(walker[i,1:2]),vpl,returnList=
TRUE)[[1]])). I thought maybe this was a boundary issue, but the points
don't lie on the edge, nor are they the centroid.

Any help you can provide would be greatly appreciated!

Regards,

Alan

R-Script Below:

### Help Question for  r-sig-geo ###
> rm(list = ls())
> library(deldir)
> library(sp)
> library(plyr)
> side_length = 100
> ## Create random SET of XY coordinates (size = 100x100)
> set.seed(11)
> df = data.frame(matrix(sample(1:100,16,replace=TRUE),nrow=8))
> ## Convert df to SPatialPointsDataFrame
> spdf <- SpatialPointsDataFrame(df,df)
> ## deldir() function creates tesselation (voronoi) plot
> z <- deldir(df,plotit=TRUE,wl='te')
> ## tile.list() creates a list of data for tiles
> zz <- tile.list(deldir(df,plotit=TRUE,wl='te'))
> ## Voronoi Polygons Function
> voronoipolygons = function(layer) {
>   require(deldir)
>   crds = layer@coords
>   z = deldir(crds[,1], crds[,2])
>   w = tile.list(z)
>   polys = vector(mode='list', length=length(w))
>   require(sp)
>   for (i in seq(along=polys)) {
> pcrds = cbind(w[[i]]$x, w[[i]]$y)
> pcrds = rbind(pcrds, pcrds[1,])
> polys[[i]] = Polygons(list(Polygon(pcrds)), ID=as.character(i))
>   }
>   SP = SpatialPolygons(polys)
>   voronoi = SpatialPolygonsDataFrame(SP, data=data.frame(x=crds[,1],
> y=crds[,2], row.names=sapply(slot(SP, 'polygons'),
> function(x) slot(x, 'ID'
> }
> ## Generate SpatialPolygonsDataFrame to use as input for over() function
> vpl <- voronoipolygons(spdf)
> ## Random Walk Function generates North, South East or West movement
> ## with transit from across screen (like PacMan, going out one side,
> ## coming back on the other side) to prevent getting stuck in corner
> random_walk <- function(step_quantity, step_length, plot = FALSE){
>   require(ggplot2)
>
>   walker <- data.frame(matrix(c(0,0), nrow = step_quantity, ncol = 3,
> byrow = T))
>   names(walker)[1]<-paste("x")
>   names(walker)[2]<-paste("y")
>   names(walker)[3]<-paste("which")
>
>   ## Seed random initial starting point
>   walker[1,1:2] <- matrix(sample(1:100,2,replace=TRUE),nrow=1)
>   walker[1,3] <-
> as.numeric(rownames(over(SpatialPoints(walker[1,1:2]),vpl,returnList=
> TRUE)[[1]]))
>
>   where_to <- as.numeric()
>
>   for(i in 2:step_quantity){
> where_to <- as.numeric()
> where_to <- walker[i-1,1:2]
> which_next <- sample(c("bb","dd","ff","hh"),1)
>
> if (which_next == "bb") {
>   if (walker[i-1,2] == side_length) {where_to[1,2] <- 0
>   } else {where_to[1,2] <- walker[i-1,2]+step_length}
> }
>
> else if (which_next == "dd") {
>   if (walker[i-1,1] == 0 ) {where_to[1,1] <- side_length
>   } else {where_to[1,1] <- walker[i-1,1]-step_length}
> }
>
> else if (which_next == "ff") {
>   if (walker[i-1,1] == side_length) {where_to[1,1] <- 0
>   } else {where_to[1,1] <- walker[i-1,1]+step_length}
> }
> else {
>   if (walker[i-1,2] == 0) {where_to[1,2] <- side_length
>   } else {where_to[1,2] <- walker[i-1,2]-step_length}
> }
>
> walker[i,1:2] <- where_to
>   }
>
>   walker[i,3] <- as.numeric(rownames(over(SpatialPoints(walker[i,1:2]),
>   vpl,returnList= TRUE)[[1]]))
>
>
>   if(plot){
>   require(ggplot2)
>   p <- ggplot(walker, aes(x = x, y = y))
>   p <- p + geom_path()
>   print(p)
>   }
>
>   return(walker)
> }
> try(transits <- random_walk(5000,1),silent=F)

[[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 on pointLabel() function for engineering drawings

2015-09-28 Thread Dhiraj Khanna
Oscar, I did as you suggested by putting “” for labels that I didn’t want.
However, the labels still overlap the drawing :( Here is my code:

library(dplyr)library(maptools)#Known Size of Sheet
xmin <- -357.7
xmax <- 19.3
ymin <- -90.2
ymax <- 159.7
#Read in the data
linescoords <- read.csv("Linecoords.csv")
#Coordinates translation
linescoords$X  <- linescoords$X - xmin
linescoords$Y <- linescoords$Y - ymin
# Plot the figure
xlimit <- c(-10, abs(xmin-xmax)+10 )
ylimit <- c(-10, abs(ymin-ymax)+10 )
plot(linescoords$X, linescoords$Y, "p", xlim=xlimit, ylim = ylimit)

i <- seq(1, nrow(linescoords), 2)for(x in i){
  segments(linescoords$X[x], linescoords$Y[x],
   linescoords$X[x+1], linescoords$Y[x+1])
}
#Read in text labels data
labels <- read.csv("labels.csv")
#Text labels Coordinates translation
labels$x <- labels$x - xmin
labels$y <- labels$y - ymin
labels$xminl <- labels$xminl - xmin
labels$xmaxl <- labels$xmaxl - xmin
labels$yminl <- labels$yminl - ymin
labels$ymaxl <- labels$ymaxl - ymin
#Point of Origin for labels
points(labels$x, labels$y, pch=16, col="red")
#Width & Height of labels
labels <- labels %>% mutate(width=abs(xminl-xmaxl), height=abs(yminl-ymaxl))

oddseq <- seq(1, nrow(linescoords),2)
evenseq <- seq(2, nrow(linescoords),2)

x1 <- linescoords$X[oddseq]
y1 <- linescoords$Y[oddseq]
x2 <- linescoords$X[evenseq]
y2 <- linescoords$Y[evenseq]
lineseg <- seq(1,length(x1))

lineslope <- as.data.frame(cbind(lineseg, x1, y1, x2, y2))

lineslope <- mutate(lineslope, slope=(y2-y1)/(x2-x1))

pointsx <- vector("list")
pointsy <- vector("list")for (s in 1:nrow(lineslope)){

  if(lineslope[s,2]==lineslope[s,4]){
  louty <- abs(lineslope[s,3]-lineslope[s,5])/3
  yp <- seq(lineslope[s,3], lineslope[s,5], length.out=louty)
  pointsy[[s]] <- yp
  xp <- seq(lineslope[s,2], lineslope[s,4], length.out=louty)
  pointsx[[s]] <- xp
  }
  else{
loutx <- abs(lineslope[s,2]-lineslope[s,4])/3
xp <- seq(lineslope[s,2], lineslope[s,4], length.out=loutx)
pointsx[[s]] <- xp
yp <- seq(lineslope[s,3], lineslope[s,5], length.out=loutx)
pointsy[[s]] <- yp
  }
}

finalx <- unlist(pointsx)
finaly <- unlist(pointsy)

extralabels <- vector("character", length=length(finalx))
labelsfinal <- append(as.character(labels$Point), extralabels)
X <- append(labels$x, finalx)
Y <- append(labels$y, finaly)
plot(finalx, finaly, "p")
pointLabel(X, Y, labelsfinal)
points(labels$x, labels$y, pch=16, col="red")

​

Regards

Dhiraj Khanna
Mob:09873263331

On Sun, Sep 27, 2015 at 9:58 PM, Oscar Perpiñán Lamigueiro <
oscar.perpi...@upm.es> wrote:

> > Will using the lineLabel function align the labels as per the
> > orientation of the line?
>
> Yes, exactly.
>
> > Also, I changed the lines to points and then tried the pointLabel
> > function.  However, it ignores all the points that are not mentioned
> > in the argument of the function and still plots over them. Any
> > workaround for this?
>
> You may include empty characters ("") as elements in the _labels_
> vector. For example:
>
> x <- 1:5
> y <- 1:5
> labels <- c('A', 'B', '', 'D', '')
> plot(x, y)
> pointLabel(x, y, labels)
>
> Best.
>
> Oscar.
>
> --
> Oscar Perpiñán Lamigueiro
> Dpto. Ing. Eléctrica, Electrónica, Automática y Física Aplicada
> Escuela Técnica Superior de Ingeniería y Diseño Industrial
> URL: http://oscarperpinan.github.io
>
___
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 on pointLabel() function for engineering drawings

2015-09-27 Thread Oscar Perpiñán Lamigueiro
> Will using the lineLabel function align the labels as per the
> orientation of the line?

Yes, exactly.

> Also, I changed the lines to points and then tried the pointLabel
> function.  However, it ignores all the points that are not mentioned
> in the argument of the function and still plots over them. Any
> workaround for this?

You may include empty characters ("") as elements in the _labels_
vector. For example:

x <- 1:5
y <- 1:5
labels <- c('A', 'B', '', 'D', '')
plot(x, y)
pointLabel(x, y, labels)

Best.

Oscar.

-- 
Oscar Perpiñán Lamigueiro
Dpto. Ing. Eléctrica, Electrónica, Automática y Física Aplicada
Escuela Técnica Superior de Ingeniería y Diseño Industrial
URL: http://oscarperpinan.github.io

___
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 on pointLabel() function for engineering drawings

2015-09-26 Thread Oscar Perpiñán Lamigueiro
Hi,

You could try the `lineLabel` and `sp.lineLabel` functions of this same
package.

Best.

Oscar.
-- 
Oscar Perpiñán Lamigueiro
Dpto. Ing. Eléctrica, Electrónica, Automática y Física Aplicada
Escuela Técnica Superior de Ingeniería y Diseño Industrial
URL: http://oscarperpinan.github.io

___
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 on pointLabel() function for engineering drawings

2015-09-26 Thread Roger Bivand

On Sat, 26 Sep 2015, Dhiraj Khanna wrote:


Thank you Oscar for the reply. Will try as you suggest. However, must admit
that I am quite a noob when it comes to plotting. Was looking at your
lineLabel() function and couldn't figure out what a "list of lines" is.
Anyway, will struggle a little and do my homework. Just one question
though. Will using the lineLabel function align the labels as per the
orientation of the line? If so, that is not what I need. The labels need to
be straight.

Also, I changed the lines to points and then tried the pointLabel function.
However, it ignores all the points that are not mentioned in the argument
of the function and still plots over them. Any workaround for this?


Maybe also see rgeos::polygonsLabel(), by Karl Ove Hufthammer, to compute 
optimal label positions for polygons - if your background data can be 
represented as a SpatialPolygons object.


Roger



Regards

Dhiraj Khanna
Mob:09873263331

2015-09-26 12:45 GMT+05:30 Oscar Perpiñán Lamigueiro 
:


Hi,

You could try the `lineLabel` and `sp.lineLabel` functions of this same
package.

Best.

Oscar.
--
Oscar Perpiñán Lamigueiro
Dpto. Ing. Eléctrica, Electrónica, Automática y Física Aplicada
Escuela Técnica Superior de Ingeniería y Diseño Industrial
URL: http://oscarperpinan.github.io



[[alternative HTML version deleted]]

___
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; fax +47 55 95 91 00
e-mail: roger.biv...@nhh.no
___
R-sig-Geo mailing list
R-sig-Geo@r-project.org
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


[R-sig-Geo] Help on pointLabel() function for engineering drawings

2015-09-24 Thread Dhiraj Khanna
Hello,



I am trying to solve automatic label placement problem for an engineering
drawing using the Simulated Annealing algorithm. I came across the
pointLabel() function in the maptools library in R. However, what I found
was that while the function is able to optimally place the labels, it
doesn't take into account the underlying drawing. I don't want the labels
to overlap with the drawing lines. Is there some way I can achieve this?
Also, my labels are of varying size in terms of width and height. Is there
any way in which I can specify the dimension of each label apart from the
point of origin of the labels?

This is my code and a link to the requisite csv files:
https://www.dropbox.com/s/85qqs4nlvm4crck/TextBoxData.rar?dl=0

library(dplyr)
library(maptools)
#Known Size of Sheet
xmin <- -357.7
xmax <- 19.3
ymin <- -90.2
ymax <- 159.7
#Read in the data
linescoords <- read.csv("Linecoords.csv")
#Coordinates translation
linescoords$X  <- linescoords$X - xmin
linescoords$Y <- linescoords$Y - ymin
#Plot the figure
xlimit <- c(-10, abs(xmin-xmax)+10 )
ylimit <- c(-10, abs(ymin-ymax)+10 )
plot(linescoords$X, linescoords$Y, "p", xlim=xlimit, ylim = ylimit)

i <- seq(1, nrow(linescoords), 2)for(x in i){
segments(linescoords$X[x], linescoords$Y[x],
 linescoords$X[x+1], linescoords$Y[x+1])}

#Read in text labels data
labels <- read.csv("labels.csv")
#Text labels Coordinates translation
labels$x <- labels$x - xmin
labels$y <- labels$y - ymin
labels$xminl <- labels$xminl - xmin
labels$xmaxl <- labels$xmaxl - xmin
labels$yminl <- labels$yminl - ymin
labels$ymaxl <- labels$ymaxl - ymin
#Point of Origin for labels
points(labels$x, labels$y, pch=16, col="red")
#Width & Height of labels
labels <- labels %>% mutate(width=abs(xminl-xmaxl), height=abs(yminl-ymaxl))

pointLabel(labels$x, labels$y, labels$Point)

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


Re: [R-sig-Geo] [Help] Error in spChFIDs(SP, x) : lengths differ

2015-09-05 Thread Robert J. Hijmans
There is no need to 'make a copy of the attribute table' of the sp
object. Instead, you should be able to do:

 library(sp)
 # From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
 states  <- readOGR(dsn = "./cb_2014_us_state_5m.shp", layer =
"cb_2014_us_state_5m")
 states <- merge(states, counts)
 states <- states[-which(states$STUSPS == "PR"),]

Robert


On Fri, Sep 4, 2015 at 8:59 AM, Ignacio Martinez  wrote:
> I'm not sure what I'm missing. This is not working (same error):
>
> counts <-
>   structure(
> list(
>   STUSPS = c(
> "CA", "NC", "TX", "FL", "VA", "OH",
> "NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC", "KS",
> "DC",
> "TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY", "OK",
> "MO",
> "ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT", "IA",
> "MT",
> "HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME", "RI",
> "NH",
> "DE", "PR", "GU", "VI", "MP", "AS"
>   ), count = c(
> 36511L, 27513L,
> 25861L, 21099L, 19415L, 17012L, 15860L, 14362L, 13923L, 13753L,
> 11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L, 8076L, 7985L,
> 7770L, 7662L, 7531L, 7273L, 7212L, 7042L, 6708L, 6674L, 6429L,
> 6239L, 5580L, 5395L, 5172L, 5013L, 4933L, 4911L, 4797L, 4694L,
> 4458L, 3873L, 3757L, 3608L, 3111L, 2604L, 2217L, 2156L, 2143L,
> 2030L, 1544L, 1417L, 1168L, 772L, 531L, 148L, 63L, 7L, 2L
>   )
> ), .Names = c("STUSPS",
>   "count"), class = c("tbl_df", "tbl", "data.frame"),
> row.names = c(NA,-56L)
>   )
>
>
> x = c("leaflet", "rgdal", "maptools", "mapproj", "rgeos", "dplyr", "sp")
> lapply(x, library, character.only = TRUE)
> # From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
> states  <- readOGR(dsn = "./cb_2014_us_state_5m.shp",
>layer = "cb_2014_us_state_5m", verbose = FALSE)
> # Make a copy of the SPDF attribute table, and then work normally, as
> with any data.frame/data.table object
> states.df <- states@data
> # Create an explicit attribute to keep polygons IDs (useful to
> "re-attach" the table to the polygons later)
> states.df <- states.df %>% mutate(rn=row.names(states))
>
> # join them
>
> US = merge(states.df, counts) # uses sp::merge.Spatial
> US = US[-which(US$STUSPS == "PR"),]
>
>
> # Re-attach the attribute table to the SPDF
> states@data <- US
> # Make sure polygons IDs and data.frame row.names match
> states <- spChFIDs(states, states$rn)
>
> Thanks!
>
> On Fri, Sep 4, 2015 at 11:47 AM Edzer Pebesma 
> wrote:
>
>> On 09/04/2015 03:53 PM, Ignacio Martinez wrote:
>> > Thanks Edzer. I think I understand the problem better now (this is all
>> > very new to me). Is there a solution so I can generate the map with my
>> data?
>> >
>>
>> The STUSPS fields of counts and states match, but you seem to filter the
>> attribute table after you merged counts and states, which drops PR, but
>> doesn't take it out of states:
>>
>> > match(c("PR", "na", "MH", "FM", "PW"), counts$STUSPS)
>> [1] 52 NA NA NA NA
>>
>> So, in case you want to deselect PR, a shorter way to get there is
>>
>> > m = merge(states, counts) # uses sp::merge.Spatial
>> > m = m[-which(m$STUSPS == "PR"),]
>> > length(m)
>> [1] 55
>>
>>
>>
>> > Thanks again!
>> >
>> > On Fri, Sep 4, 2015 at 9:51 AM Edzer Pebesma
>> > >
>> > wrote:
>> >
>> >
>> >
>> > On 09/04/2015 03:29 PM, Ignacio Martinez wrote:
>> > > I'm trying to create a map using leaflet. I'm basically following
>> this
>> > > but my data is a
>> bit
>> > > different this time around. Additionally, I'm using dplyr instead
>> of
>> > > data.table.
>> > >
>> > > This is the code i'm trying to run:
>> > >
>> > > counts <-
>> > >   structure(
>> > > list(
>> > >   STUSPS = c(
>> > > "CA", "NC", "TX", "FL", "VA", "OH",
>> > > "NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC",
>> > "KS",
>> > > "DC",
>> > > "TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY",
>> > "OK",
>> > > "MO",
>> > > "ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT",
>> > "IA",
>> > > "MT",
>> > > "HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME",
>> > "RI",
>> > > "NH",
>> > > "DE", "PR", "GU", "VI", "MP", "AS"
>> > >   ), count = c(
>> > > 36511L, 27513L,
>> > > 25861L, 21099L, 19415L, 17012L, 15860L, 14362L,
>> > 13923L, 13753L,
>> > > 11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L,
>> > 8076L, 7985L,
>> > > 

Re: [R-sig-Geo] [Help] Error in spChFIDs(SP, x) : lengths differ

2015-09-04 Thread Ignacio Martinez
Thanks Edzer. I think I understand the problem better now (this is all very
new to me). Is there a solution so I can generate the map with my data?

Thanks again!

On Fri, Sep 4, 2015 at 9:51 AM Edzer Pebesma 
wrote:

>
>
> On 09/04/2015 03:29 PM, Ignacio Martinez wrote:
> > I'm trying to create a map using leaflet. I'm basically following this
> > but my data is a bit
> > different this time around. Additionally, I'm using dplyr instead of
> > data.table.
> >
> > This is the code i'm trying to run:
> >
> > counts <-
> >   structure(
> > list(
> >   STUSPS = c(
> > "CA", "NC", "TX", "FL", "VA", "OH",
> > "NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC", "KS",
> > "DC",
> > "TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY", "OK",
> > "MO",
> > "ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT", "IA",
> > "MT",
> > "HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME", "RI",
> > "NH",
> > "DE", "PR", "GU", "VI", "MP", "AS"
> >   ), count = c(
> > 36511L, 27513L,
> > 25861L, 21099L, 19415L, 17012L, 15860L, 14362L, 13923L,
> 13753L,
> > 11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L, 8076L,
> 7985L,
> > 7770L, 7662L, 7531L, 7273L, 7212L, 7042L, 6708L, 6674L,
> 6429L,
> > 6239L, 5580L, 5395L, 5172L, 5013L, 4933L, 4911L, 4797L,
> 4694L,
> > 4458L, 3873L, 3757L, 3608L, 3111L, 2604L, 2217L, 2156L,
> 2143L,
> > 2030L, 1544L, 1417L, 1168L, 772L, 531L, 148L, 63L, 7L, 2L
> >   )
> > ), .Names = c("STUSPS",
> >   "count"), class = c("tbl_df", "tbl", "data.frame"),
> > row.names = c(NA,-56L)
> >   )
> >
> >
> > x = c("leaflet", "rgdal", "maptools", "mapproj", "rgeos", "dplyr")
> > lapply(x, library, character.only = TRUE)
> > # From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
> > states  <- readOGR(dsn = "./cb_2014_us_state_5m.shp",
> >layer = "cb_2014_us_state_5m", verbose = FALSE)
> > # Make a copy of the SPDF attribute table, and then work normally, as
> > with any data.frame/data.table object
> > states.df <- states@data
> > # Create an explicit attribute to keep polygons IDs (useful to
> > "re-attach" the table to the polygons later)
> > states.df <- states.df %>% mutate(rn=row.names(states))
> >
> > # join them
> > states.df <- full_join(x = states.df, y = counts, by="STUSPS") %>%
> >   filter(!(STUSPS%in%c("PR", "na", "MH", "FM", "PW"))) %>% na.omit()
> %>%
> >   mutate(popup=paste0('',NAME,'','',
> >   'count: ',
> > prettyNum(count,big.mark=",",scientific=FALSE)))
>
> at this stage, you have:
>
> > dim(states@data)
> [1] 56  9
> > dim(states.df)
> [1] 55 12
>
> >
> > # Re-attach the attribute table to the SPDF
> > states@data <- states.df
>
> now, you created an invalid object:
> > length(geometry(states))
> [1] 56
> > dim(states@data)
> [1] 55 12
>
> this confirms once more what has been said on this list so often, that
> instead of using constructor functions such as
> SpatialPolygonsDataFrame(), assigning slots directly is dangerous and
> better left to those who know what they do (and check sanity):
>
> > states <- SpatialPolygonsDataFrame(geometry(states), states.df)
> Error in SpatialPolygonsDataFrame(geometry(states), states.df) :
>   Object length mismatch:
>  geometry(states) has 56 Polygons objects, but states.df has 55 rows
>
>
> > # Make sure polygons IDs and data.frame row.names match
> > states <- spChFIDs(states, states$rn)
> >
> > # Create map as usual...
> >
> > The error I get is:
> >
> > Error in spChFIDs(SP, x) : lengths differ
> >
> >
> > Thanks for the help!
> >
> >
> > Ignacio
> >
> >   [[alternative HTML version deleted]]
> >
> > ___
> > R-sig-Geo mailing list
> > R-sig-Geo@r-project.org
> > https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> >
>
> --
> 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
>

[[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] [Help] Error in spChFIDs(SP, x) : lengths differ

2015-09-04 Thread Ignacio Martinez
I'm trying to create a map using leaflet. I'm basically following this
but my data is a bit
different this time around. Additionally, I'm using dplyr instead of
data.table.

This is the code i'm trying to run:

counts <-
  structure(
list(
  STUSPS = c(
"CA", "NC", "TX", "FL", "VA", "OH",
"NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC", "KS",
"DC",
"TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY", "OK",
"MO",
"ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT", "IA",
"MT",
"HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME", "RI",
"NH",
"DE", "PR", "GU", "VI", "MP", "AS"
  ), count = c(
36511L, 27513L,
25861L, 21099L, 19415L, 17012L, 15860L, 14362L, 13923L, 13753L,
11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L, 8076L, 7985L,
7770L, 7662L, 7531L, 7273L, 7212L, 7042L, 6708L, 6674L, 6429L,
6239L, 5580L, 5395L, 5172L, 5013L, 4933L, 4911L, 4797L, 4694L,
4458L, 3873L, 3757L, 3608L, 3111L, 2604L, 2217L, 2156L, 2143L,
2030L, 1544L, 1417L, 1168L, 772L, 531L, 148L, 63L, 7L, 2L
  )
), .Names = c("STUSPS",
  "count"), class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA,-56L)
  )


x = c("leaflet", "rgdal", "maptools", "mapproj", "rgeos", "dplyr")
lapply(x, library, character.only = TRUE)
# From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
states  <- readOGR(dsn = "./cb_2014_us_state_5m.shp",
   layer = "cb_2014_us_state_5m", verbose = FALSE)
# Make a copy of the SPDF attribute table, and then work normally, as
with any data.frame/data.table object
states.df <- states@data
# Create an explicit attribute to keep polygons IDs (useful to
"re-attach" the table to the polygons later)
states.df <- states.df %>% mutate(rn=row.names(states))

# join them
states.df <- full_join(x = states.df, y = counts, by="STUSPS") %>%
  filter(!(STUSPS%in%c("PR", "na", "MH", "FM", "PW"))) %>% na.omit() %>%
  mutate(popup=paste0('',NAME,'','',
  'count: ',
prettyNum(count,big.mark=",",scientific=FALSE)))

# Re-attach the attribute table to the SPDF
states@data <- states.df
# Make sure polygons IDs and data.frame row.names match
states <- spChFIDs(states, states$rn)

# Create map as usual...

The error I get is:

Error in spChFIDs(SP, x) : lengths differ


Thanks for the help!


Ignacio

[[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] Error in spChFIDs(SP, x) : lengths differ

2015-09-04 Thread Edzer Pebesma


On 09/04/2015 03:29 PM, Ignacio Martinez wrote:
> I'm trying to create a map using leaflet. I'm basically following this
> but my data is a bit
> different this time around. Additionally, I'm using dplyr instead of
> data.table.
> 
> This is the code i'm trying to run:
> 
> counts <-
>   structure(
> list(
>   STUSPS = c(
> "CA", "NC", "TX", "FL", "VA", "OH",
> "NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC", "KS",
> "DC",
> "TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY", "OK",
> "MO",
> "ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT", "IA",
> "MT",
> "HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME", "RI",
> "NH",
> "DE", "PR", "GU", "VI", "MP", "AS"
>   ), count = c(
> 36511L, 27513L,
> 25861L, 21099L, 19415L, 17012L, 15860L, 14362L, 13923L, 13753L,
> 11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L, 8076L, 7985L,
> 7770L, 7662L, 7531L, 7273L, 7212L, 7042L, 6708L, 6674L, 6429L,
> 6239L, 5580L, 5395L, 5172L, 5013L, 4933L, 4911L, 4797L, 4694L,
> 4458L, 3873L, 3757L, 3608L, 3111L, 2604L, 2217L, 2156L, 2143L,
> 2030L, 1544L, 1417L, 1168L, 772L, 531L, 148L, 63L, 7L, 2L
>   )
> ), .Names = c("STUSPS",
>   "count"), class = c("tbl_df", "tbl", "data.frame"),
> row.names = c(NA,-56L)
>   )
> 
> 
> x = c("leaflet", "rgdal", "maptools", "mapproj", "rgeos", "dplyr")
> lapply(x, library, character.only = TRUE)
> # From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
> states  <- readOGR(dsn = "./cb_2014_us_state_5m.shp",
>layer = "cb_2014_us_state_5m", verbose = FALSE)
> # Make a copy of the SPDF attribute table, and then work normally, as
> with any data.frame/data.table object
> states.df <- states@data
> # Create an explicit attribute to keep polygons IDs (useful to
> "re-attach" the table to the polygons later)
> states.df <- states.df %>% mutate(rn=row.names(states))
> 
> # join them
> states.df <- full_join(x = states.df, y = counts, by="STUSPS") %>%
>   filter(!(STUSPS%in%c("PR", "na", "MH", "FM", "PW"))) %>% na.omit() %>%
>   mutate(popup=paste0('',NAME,'','',
>   'count: ',
> prettyNum(count,big.mark=",",scientific=FALSE)))

at this stage, you have:

> dim(states@data)
[1] 56  9
> dim(states.df)
[1] 55 12

> 
> # Re-attach the attribute table to the SPDF
> states@data <- states.df

now, you created an invalid object:
> length(geometry(states))
[1] 56
> dim(states@data)
[1] 55 12

this confirms once more what has been said on this list so often, that
instead of using constructor functions such as
SpatialPolygonsDataFrame(), assigning slots directly is dangerous and
better left to those who know what they do (and check sanity):

> states <- SpatialPolygonsDataFrame(geometry(states), states.df)
Error in SpatialPolygonsDataFrame(geometry(states), states.df) :
  Object length mismatch:
 geometry(states) has 56 Polygons objects, but states.df has 55 rows


> # Make sure polygons IDs and data.frame row.names match
> states <- spChFIDs(states, states$rn)
> 
> # Create map as usual...
> 
> The error I get is:
> 
> Error in spChFIDs(SP, x) : lengths differ
> 
> 
> Thanks for the help!
> 
> 
> Ignacio
> 
>   [[alternative HTML version deleted]]
> 
> ___
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
> 

-- 
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



signature.asc
Description: OpenPGP digital signature
___
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] Error in spChFIDs(SP, x) : lengths differ

2015-09-04 Thread Ignacio Martinez
I'm not sure what I'm missing. This is not working (same error):

counts <-
  structure(
list(
  STUSPS = c(
"CA", "NC", "TX", "FL", "VA", "OH",
"NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC", "KS",
"DC",
"TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY", "OK",
"MO",
"ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT", "IA",
"MT",
"HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME", "RI",
"NH",
"DE", "PR", "GU", "VI", "MP", "AS"
  ), count = c(
36511L, 27513L,
25861L, 21099L, 19415L, 17012L, 15860L, 14362L, 13923L, 13753L,
11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L, 8076L, 7985L,
7770L, 7662L, 7531L, 7273L, 7212L, 7042L, 6708L, 6674L, 6429L,
6239L, 5580L, 5395L, 5172L, 5013L, 4933L, 4911L, 4797L, 4694L,
4458L, 3873L, 3757L, 3608L, 3111L, 2604L, 2217L, 2156L, 2143L,
2030L, 1544L, 1417L, 1168L, 772L, 531L, 148L, 63L, 7L, 2L
  )
), .Names = c("STUSPS",
  "count"), class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA,-56L)
  )


x = c("leaflet", "rgdal", "maptools", "mapproj", "rgeos", "dplyr", "sp")
lapply(x, library, character.only = TRUE)
# From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
states  <- readOGR(dsn = "./cb_2014_us_state_5m.shp",
   layer = "cb_2014_us_state_5m", verbose = FALSE)
# Make a copy of the SPDF attribute table, and then work normally, as
with any data.frame/data.table object
states.df <- states@data
# Create an explicit attribute to keep polygons IDs (useful to
"re-attach" the table to the polygons later)
states.df <- states.df %>% mutate(rn=row.names(states))

# join them

US = merge(states.df, counts) # uses sp::merge.Spatial
US = US[-which(US$STUSPS == "PR"),]


# Re-attach the attribute table to the SPDF
states@data <- US
# Make sure polygons IDs and data.frame row.names match
states <- spChFIDs(states, states$rn)

Thanks!

On Fri, Sep 4, 2015 at 11:47 AM Edzer Pebesma 
wrote:

> On 09/04/2015 03:53 PM, Ignacio Martinez wrote:
> > Thanks Edzer. I think I understand the problem better now (this is all
> > very new to me). Is there a solution so I can generate the map with my
> data?
> >
>
> The STUSPS fields of counts and states match, but you seem to filter the
> attribute table after you merged counts and states, which drops PR, but
> doesn't take it out of states:
>
> > match(c("PR", "na", "MH", "FM", "PW"), counts$STUSPS)
> [1] 52 NA NA NA NA
>
> So, in case you want to deselect PR, a shorter way to get there is
>
> > m = merge(states, counts) # uses sp::merge.Spatial
> > m = m[-which(m$STUSPS == "PR"),]
> > length(m)
> [1] 55
>
>
>
> > Thanks again!
> >
> > On Fri, Sep 4, 2015 at 9:51 AM Edzer Pebesma
> > >
> > wrote:
> >
> >
> >
> > On 09/04/2015 03:29 PM, Ignacio Martinez wrote:
> > > I'm trying to create a map using leaflet. I'm basically following
> this
> > > but my data is a
> bit
> > > different this time around. Additionally, I'm using dplyr instead
> of
> > > data.table.
> > >
> > > This is the code i'm trying to run:
> > >
> > > counts <-
> > >   structure(
> > > list(
> > >   STUSPS = c(
> > > "CA", "NC", "TX", "FL", "VA", "OH",
> > > "NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC",
> > "KS",
> > > "DC",
> > > "TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY",
> > "OK",
> > > "MO",
> > > "ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT",
> > "IA",
> > > "MT",
> > > "HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME",
> > "RI",
> > > "NH",
> > > "DE", "PR", "GU", "VI", "MP", "AS"
> > >   ), count = c(
> > > 36511L, 27513L,
> > > 25861L, 21099L, 19415L, 17012L, 15860L, 14362L,
> > 13923L, 13753L,
> > > 11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L,
> > 8076L, 7985L,
> > > 7770L, 7662L, 7531L, 7273L, 7212L, 7042L, 6708L,
> > 6674L, 6429L,
> > > 6239L, 5580L, 5395L, 5172L, 5013L, 4933L, 4911L,
> > 4797L, 4694L,
> > > 4458L, 3873L, 3757L, 3608L, 3111L, 2604L, 2217L,
> > 2156L, 2143L,
> > > 2030L, 1544L, 1417L, 1168L, 772L, 531L, 148L, 63L, 7L,
> 2L
> > >   )
> > > ), .Names = c("STUSPS",
> > >   "count"), class = c("tbl_df", "tbl",
> > "data.frame"),
> > > row.names = c(NA,-56L)
> > >   )
> > >
> > >
> > > x = c("leaflet", "rgdal", "maptools", 

Re: [R-sig-Geo] [Help] Error in spChFIDs(SP, x) : lengths differ

2015-09-04 Thread Ignacio Martinez
This works :-) :

library(dplyr)
library(leaflet)
library(rgdal)
library(sp)
states  <- rgdal::readOGR(dsn = "./cb_2014_us_state_5m.shp",
  layer = "cb_2014_us_state_5m", verbose =
FALSE)

statesnames <-
  states@data %>% mutate(STUSPS = as.character(STUSPS)) %>%
select(NAME, STUSPS)

counts <-
  structure(
list(
  STUSPS = c(
"TX", "CA", "FL", "OH", "NY", "CO",
"MI", "IL", "PA", "NJ", "VA", "NC", "GA", "WA", "MN", "MD",
"AZ",
"IA", "MA", "WI", "TN", "LA", "IN", "SC", "KY", "ID", "MO",
"AL",
"OK", "CT", "KS", "OR", "UT", "NE", "ND", "NV", "MS", "AR",
"SD",
"MT", "DC", "WY", "AK", "NM", "HI", "NH", "WV", "ME", "RI",
"DE",
"VT", "PR", "VI"
  ), count = c(
12031L, 11968L, 7232L, 5113L, 4733L,
4392L, 4251L, 4168L, 3640L, 3374L, 3371L, 3284L, 3084L, 2837L,
2662L, 2650L, 2528L, 2414L, 2378L, 2373L, 2236L, 2158L, 2120L,
1959L, 1758L, 1700L, 1547L, 1466L, 1445L, 1345L, 1305L, 1297L,
1253L, 1234L, 1166L, 1063L, 981L, 963L, 915L, 718L, 673L, 653L,
650L, 637L, 579L, 561L, 510L, 496L, 486L, 396L, 273L, 6L, 5L
  )
), .Names = c("STUSPS",
  "count"), class = c("tbl_df", "tbl", "data.frame"),
row.names = c(NA,-53L)
  )

counts <- counts %>% inner_join(statesnames, by = "STUSPS") %>%
  mutate(popup = paste0(
'',NAME,'','',
'Number: ', prettyNum(count,big.mark = ",",scientific =
  FALSE)
  ))


USA <- merge(states, counts) # uses sp::merge.Spatial
USA <- USA[-which(USA$STUSPS %in% as.character(USA@data$STUSPS[is.na
(USA@data$count)])),]

pal <- colorNumeric(
  palette = "Greens",
  domain = USA$count)

leaflet(USA, height = "490px", width = "800px")  %>%
  addPolygons(
stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
color = ~ pal(count), popup = ~popup
  ) %>%
  setView(lng = -98.579394, lat = 37, zoom = 4) %>%
  addLegend(position = "bottomright",
pal = pal,
title = "Number",
opacity = 1, values = USA$count)

Please let me know if you see something that I could be doing better.

Thanks a lot!

Ignacio

On Fri, Sep 4, 2015 at 11:59 AM Ignacio Martinez 
wrote:

> I'm not sure what I'm missing. This is not working (same error):
>
> counts <-
>   structure(
> list(
>   STUSPS = c(
> "CA", "NC", "TX", "FL", "VA", "OH",
> "NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC", "KS",
> "DC",
> "TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY", "OK",
> "MO",
> "ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT", "IA",
> "MT",
> "HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME", "RI",
> "NH",
> "DE", "PR", "GU", "VI", "MP", "AS"
>   ), count = c(
> 36511L, 27513L,
> 25861L, 21099L, 19415L, 17012L, 15860L, 14362L, 13923L, 13753L,
> 11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L, 8076L,
> 7985L,
> 7770L, 7662L, 7531L, 7273L, 7212L, 7042L, 6708L, 6674L, 6429L,
> 6239L, 5580L, 5395L, 5172L, 5013L, 4933L, 4911L, 4797L, 4694L,
> 4458L, 3873L, 3757L, 3608L, 3111L, 2604L, 2217L, 2156L, 2143L,
> 2030L, 1544L, 1417L, 1168L, 772L, 531L, 148L, 63L, 7L, 2L
>   )
> ), .Names = c("STUSPS",
>   "count"), class = c("tbl_df", "tbl", "data.frame"),
> row.names = c(NA,-56L)
>   )
>
>
> x = c("leaflet", "rgdal", "maptools", "mapproj", "rgeos", "dplyr",
> "sp")
> lapply(x, library, character.only = TRUE)
> # From https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
> states  <- readOGR(dsn = "./cb_2014_us_state_5m.shp",
>layer = "cb_2014_us_state_5m", verbose = FALSE)
> # Make a copy of the SPDF attribute table, and then work normally, as
> with any data.frame/data.table object
> states.df <- states@data
> # Create an explicit attribute to keep polygons IDs (useful to
> "re-attach" the table to the polygons later)
> states.df <- states.df %>% mutate(rn=row.names(states))
>
> # join them
>
> US = merge(states.df, counts) # uses sp::merge.Spatial
> US = US[-which(US$STUSPS == "PR"),]
>
>
> # Re-attach the attribute table to the SPDF
> states@data <- US
> # Make sure polygons IDs and data.frame row.names match
> states <- spChFIDs(states, states$rn)
>
> Thanks!
>
> On Fri, Sep 4, 2015 at 11:47 AM Edzer Pebesma <
> edzer.pebe...@uni-muenster.de> wrote:
>
>> On 09/04/2015 03:53 PM, Ignacio Martinez wrote:
>> > Thanks Edzer. I think I understand the problem better now (this is all
>> > very new to me). Is there a solution so I can generate the map with my
>> data?
>> >
>>
>> The 

Re: [R-sig-Geo] [Help] Error in spChFIDs(SP, x) : lengths differ

2015-09-04 Thread Edzer Pebesma
On 09/04/2015 03:53 PM, Ignacio Martinez wrote:
> Thanks Edzer. I think I understand the problem better now (this is all
> very new to me). Is there a solution so I can generate the map with my data?
> 

The STUSPS fields of counts and states match, but you seem to filter the
attribute table after you merged counts and states, which drops PR, but
doesn't take it out of states:

> match(c("PR", "na", "MH", "FM", "PW"), counts$STUSPS)
[1] 52 NA NA NA NA

So, in case you want to deselect PR, a shorter way to get there is

> m = merge(states, counts) # uses sp::merge.Spatial
> m = m[-which(m$STUSPS == "PR"),]
> length(m)
[1] 55



> Thanks again!
> 
> On Fri, Sep 4, 2015 at 9:51 AM Edzer Pebesma
> >
> wrote:
> 
> 
> 
> On 09/04/2015 03:29 PM, Ignacio Martinez wrote:
> > I'm trying to create a map using leaflet. I'm basically following this
> > but my data is a bit
> > different this time around. Additionally, I'm using dplyr instead of
> > data.table.
> >
> > This is the code i'm trying to run:
> >
> > counts <-
> >   structure(
> > list(
> >   STUSPS = c(
> > "CA", "NC", "TX", "FL", "VA", "OH",
> > "NY", "GA", "IL", "WA", "CO", "AZ", "MD", "LA", "SC",
> "KS",
> > "DC",
> > "TN", "MA", "MI", "MN", "NJ", "WI", "PA", "AL", "KY",
> "OK",
> > "MO",
> > "ID", "MS", "NM", "IN", "NV", "AR", "OR", "AK", "UT",
> "IA",
> > "MT",
> > "HI", "NE", "CT", "WV", "WY", "SD", "VT", "ND", "ME",
> "RI",
> > "NH",
> > "DE", "PR", "GU", "VI", "MP", "AS"
> >   ), count = c(
> > 36511L, 27513L,
> > 25861L, 21099L, 19415L, 17012L, 15860L, 14362L,
> 13923L, 13753L,
> > 11671L, 10540L, 9777L, 8923L, 8355L, 8219L, 8142L,
> 8076L, 7985L,
> > 7770L, 7662L, 7531L, 7273L, 7212L, 7042L, 6708L,
> 6674L, 6429L,
> > 6239L, 5580L, 5395L, 5172L, 5013L, 4933L, 4911L,
> 4797L, 4694L,
> > 4458L, 3873L, 3757L, 3608L, 3111L, 2604L, 2217L,
> 2156L, 2143L,
> > 2030L, 1544L, 1417L, 1168L, 772L, 531L, 148L, 63L, 7L, 2L
> >   )
> > ), .Names = c("STUSPS",
> >   "count"), class = c("tbl_df", "tbl",
> "data.frame"),
> > row.names = c(NA,-56L)
> >   )
> >
> >
> > x = c("leaflet", "rgdal", "maptools", "mapproj", "rgeos", "dplyr")
> > lapply(x, library, character.only = TRUE)
> > # From
> https://www.census.gov/geo/maps-data/data/cbf/cbf_state.html
> > states  <- readOGR(dsn = "./cb_2014_us_state_5m.shp",
> >layer = "cb_2014_us_state_5m", verbose = FALSE)
> > # Make a copy of the SPDF attribute table, and then work
> normally, as
> > with any data.frame/data.table object
> > states.df <- states@data
> > # Create an explicit attribute to keep polygons IDs (useful to
> > "re-attach" the table to the polygons later)
> > states.df <- states.df %>% mutate(rn=row.names(states))
> >
> > # join them
> > states.df <- full_join(x = states.df, y = counts, by="STUSPS") %>%
> >   filter(!(STUSPS%in%c("PR", "na", "MH", "FM", "PW"))) %>%
> na.omit() %>%
> >   mutate(popup=paste0('',NAME,'','',
> >   'count: ',
> > prettyNum(count,big.mark=",",scientific=FALSE)))
> 
> at this stage, you have:
> 
> > dim(states@data)
> [1] 56  9
> > dim(states.df)
> [1] 55 12
> 
> >
> > # Re-attach the attribute table to the SPDF
> > states@data <- states.df
> 
> now, you created an invalid object:
> > length(geometry(states))
> [1] 56
> > dim(states@data)
> [1] 55 12
> 
> this confirms once more what has been said on this list so often, that
> instead of using constructor functions such as
> SpatialPolygonsDataFrame(), assigning slots directly is dangerous and
> better left to those who know what they do (and check sanity):
> 
> > states <- SpatialPolygonsDataFrame(geometry(states), states.df)
> Error in SpatialPolygonsDataFrame(geometry(states), states.df) :
>   Object length mismatch:
>  geometry(states) has 56 Polygons objects, but states.df has 55 rows
> 
> 
> > # Make sure polygons IDs and data.frame row.names match
> > states <- spChFIDs(states, states$rn)
> >
> > # Create map as usual...
> >
> > The error I get is:
> >
> > Error in spChFIDs(SP, x) : lengths differ
> >
> >
> > Thanks for the help!
> >
> >
> > Ignacio
> >
> >   [[alternative HTML version deleted]]
> >
> > 

Re: [R-sig-Geo] Help needed with extraction of raster statistics by polygons

2015-08-25 Thread Dominik Schneider
Denys,
The GIS functions in R have great utility, but speed is an issue; extract()
in particular. So, if you make a 30m raster equivalent to the Grid30m but
with the cell numbers as the values, you can use extract just once to
determine which cells are to be extracted with each polygon. Then use
regular indexing to find the mean for the raster cells covered by each
polygon. This should be much faster.
Dominik

Dominik Schneider
o 303.735.6296 | c 518.956.3978


On Tue, Aug 25, 2015 at 9:26 AM, Denys Dukhovnov via R-sig-Geo 
r-sig-geo@r-project.org wrote:

 Hello all!

 I need to spatially calculate 30-meter grid raster mean over US Census
 blocks in North East region (approx. 1.9 mln street blocks/polygons). I
 came up with the script that runs in parallel, but it still takes days to
 complete, even when the i7 CPU is used up to the max. My question: is there
 any other way to improve the processing speed given the set-up below (I
 included the backbone of the script to save space). I am new to R, so any
 help will be much appreciated. Thanks a lot!

 Regards,
 Denys
 

 library(sp)
 library(rgdal)
 library(raster)
 library(foreach)
 library(spatial.tools)

 Grid30m - raster(raster.tif)# loading main raster into R
 NEfips - c(09, 10, 11, )   # list of state FIPS codes, whose
 street block polygons are to be processed
 ShapePath - T:\\...  # path to block shapefiles

 sfQuickInit(cpus=8) # setting up and registering parallel
 processing back-end

 for (x in NEfips) {
 State - paste(block_, x , sep=)
 Blocks - readOGR(dsn=ShapePath, layer=State[1],
 stringsAsFactors=F)# loading the block polygons
 BlocksReproject - spTransform(Blocks, crs(Grid30m))

 GridMean - foreach (i=1:length(BlocksReproject$GEOID10),
 .combine='c', .packages=raster) %dopar% {# Parallel processing
 loop for extracting mean raster value per street block polygon
extract(Grid30m, BlocksReproject[i], fun=mean)
 }
 write.table(...)# Generating output containing the mean raster
 statistics for each block polygon.
 }

 [[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


[R-sig-Geo] Help needed with extraction of raster statistics by polygons

2015-08-25 Thread Denys Dukhovnov via R-sig-Geo
Hello all! 

I need to spatially calculate 30-meter grid raster mean over US Census blocks 
in North East region (approx. 1.9 mln street blocks/polygons). I came up with 
the script that runs in parallel, but it still takes days to complete, even 
when the i7 CPU is used up to the max. My question: is there any other way to 
improve the processing speed given the set-up below (I included the backbone of 
the script to save space). I am new to R, so any help will be much appreciated. 
Thanks a lot!

Regards,
Denys


library(sp)
library(rgdal)
library(raster)
library(foreach)
library(spatial.tools)

Grid30m - raster(raster.tif)# loading main raster into R
NEfips - c(09, 10, 11, )   # list of state FIPS codes, whose street 
block polygons are to be processed
ShapePath - T:\\...      # path to block shapefiles 

sfQuickInit(cpus=8)     # setting up and registering parallel 
processing back-end

for (x in NEfips) {
    State - paste(block_, x , sep=)
    Blocks - readOGR(dsn=ShapePath, layer=State[1], stringsAsFactors=F)    # 
loading the block polygons
    BlocksReproject - spTransform(Blocks, crs(Grid30m))
    
    GridMean - foreach (i=1:length(BlocksReproject$GEOID10), .combine='c', 
.packages=raster) %dopar% {    # Parallel processing loop for extracting 
mean raster value per street block polygon
           extract(Grid30m, BlocksReproject[i], fun=mean)
    }
    write.table(...)    # Generating output containing the mean raster 
statistics for each block polygon.
}

[[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: krigged map do not show colours

2015-08-05 Thread Jon Skoien

Anand,

I could not open your .grd file in R, I think the .gri file is missing.
However, looking at it in a text editor, and comparing with your 
R-script, it seems something went wrong with your projections. Your 
.csv-file has LatLong coordinates, but you are setting the projection to 
+proj=utm +zone=40 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84 
+towgs84=0,0,0, the same as you seem to have in your prediction raster. 
But you need to reproject your observations in this case.


# First set the right projection:
proj4string(carbon_seq) - CRS(+init=epsg4326) # epsg-code for latlong
# Then transform
carbon_seq = spTransform(carbon_seq, CRS(+proj=utm +zone=40 +south 
+datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0))


If you do this, your prediction grid should overlap your observations, 
and the colors should reflect your color ramp. What you essentially did 
before was to make a prediction thousands of km away from your 
observations, and then all values will be the same.


Best wishes,
Jon


On 8/4/2015 12:48 PM, Anand Sookun wrote:

Dear Jon and Roman

Thanks for the reply.

Im attaching the code.

You may be right that the variogram may be problematic but it fitted
well visually.

I think also that the prediction grid was not well created. I wiould be
grateful to have to hints.code how to create a useful grid and also for
the spplot or other alternatives

I can send more info if required.

Cheers

Anand

On Tue, Aug 4, 2015 at 1:39 PM, Jon Skoien jon.sko...@jrc.ec.europa.eu
mailto:jon.sko...@jrc.ec.europa.eu wrote:

Hi,

You have attached some data, but we still dont know exactly what you
do with the data (do you use the logarithm, how many bins, did you
project the data set...?). However, having had a quick look using
the LatLong coordinates (not really recommended), I can see that the
variogram from this data set is not particularly well defined, and
it could well be that you fitted a model with pure nugget effect. In
that case you will get the same prediction everywhere and no color
differences.

Have a look at
  summary(map)
and particularly the summary of var1.pred.
You could also plot the variogram of the data together with your
model, vmf, and see how they fit.

I am not sure what you mean by not being able to create a prediction
grid with data included. Do you mean that you want a grid which
exactly overlays some of the data points? Matching one point should
not be difficult, 2 and 3 should be possible, but you might get some
problems with precision (FAQ 7.31).

Best wishes,
Jon




On 8/3/2015 5:30 PM, Anand Sookun wrote:

Hi

Thank you Roman for your kind response.

The data is as attached which is part of the whole dataset.

My other problem is that im not able to create an appropriate
prediction grid with some data included.

The codes which failed to show colour ramps are

map - krige(logcarbseq ~ 1, locations = carbon_seq, newdata =
map,model = vmf)
str(map)
print(spplot(map, var1.pred, asp=1,
col.regions=bpy.colors(64),main=OK prediction, carbon))
print(spplot(map, var1.var,col.regions=cm.colors(64),asp=1,
main=OK prediction variance, carbon))

I look forward to hopefully get some solutions.

Thanks again and warm regards

Anand

On Mon, Aug 3, 2015 at 4:09 PM, Roman Luštrik
roman.lust...@gmail.com mailto:roman.lust...@gmail.com wrote:

What is the variability of the plotted variable?

Cheers,
Roman

On Sun, Aug 2, 2015 at 11:03 AM, Anand Sookun
mailto:asoo...@gmail.comasoo...@gmail.com
mailto:asoo...@gmail.com wrote:

Hi

I have kriged my data but the map shows uniform colours -
no gradual
contour colour plot on map

code: print(spplot(k40, var1.pred, asp=1,
col.regions=bpy.colors(64),main=OK prediction, log-ppm Zn))

thnaks for any help

Anand Sookun
--
---
*Anand Sookun (**MPhil. **PhD Candidate, University of
Mauritius)*
*Director cum Freelance Consultant*
*Soft Sustainable Services (Mauritius)*
*Research and Consultancy*

Website: http://sustain-ability.webs.com/



https://www.linkedin.com/profile/view?id=161468467trk=nav_responsive_tab_profile_pic

[[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




--
In God we trust, all others bring data.




--
---
/*Anand Sookun (*//*MPhil. *//*PhD Candidate, 

Re: [R-sig-Geo] help: krigged map do not show colours

2015-08-05 Thread Jon Skoien
Hi,

You have attached some data, but we still dont know exactly what you do 
with the data (do you use the logarithm, how many bins, did you project 
the data set...?). However, having had a quick look using the LatLong 
coordinates (not really recommended), I can see that the variogram from 
this data set is not particularly well defined, and it could well be 
that you fitted a model with pure nugget effect. In that case you will 
get the same prediction everywhere and no color differences.

Have a look at
  summary(map)
and particularly the summary of var1.pred.
You could also plot the variogram of the data together with your model, 
vmf, and see how they fit.

I am not sure what you mean by not being able to create a prediction 
grid with data included. Do you mean that you want a grid which exactly 
overlays some of the data points? Matching one point should not be 
difficult, 2 and 3 should be possible, but you might get some problems 
with precision (FAQ 7.31).

Best wishes,
Jon



On 8/3/2015 5:30 PM, Anand Sookun wrote:
 Hi

 Thank you Roman for your kind response.

 The data is as attached which is part of the whole dataset.

 My other problem is that im not able to create an appropriate 
 prediction grid with some data included.

 The codes which failed to show colour ramps are

 map - krige(logcarbseq ~ 1, locations = carbon_seq, newdata = 
 map,model = vmf)
 str(map)
 print(spplot(map, var1.pred, asp=1, 
 col.regions=bpy.colors(64),main=OK prediction, carbon))
 print(spplot(map, var1.var,col.regions=cm.colors(64),asp=1, main=OK 
 prediction variance, carbon))

 I look forward to hopefully get some solutions.

 Thanks again and warm regards

 Anand

 On Mon, Aug 3, 2015 at 4:09 PM, Roman Lu�trik roman.lust...@gmail.com 
 mailto:roman.lust...@gmail.com wrote:

 What is the variability of the plotted variable?

 Cheers,
 Roman

 On Sun, Aug 2, 2015 at 11:03 AM, Anand Sookun asoo...@gmail.com
 mailto:asoo...@gmail.com wrote:

 Hi

 I have kriged my data but the map shows uniform colours - no
 gradual
 contour colour plot on map

 code: print(spplot(k40, var1.pred, asp=1,
 col.regions=bpy.colors(64),main=OK prediction, log-ppm Zn))

 thnaks for any help

 Anand Sookun
 --
 ---
 *Anand Sookun (**MPhil. **PhD Candidate, University of Mauritius)*
 *Director cum Freelance Consultant*
 *Soft Sustainable Services (Mauritius)*
 *Research and Consultancy*

 Website: http://sustain-ability.webs.com/


 
 https://www.linkedin.com/profile/view?id=161468467trk=nav_responsive_tab_profile_pic

 [[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




 -- 
 In God we trust, all others bring data.




 -- 
 ---
 /*Anand Sookun (*//*MPhil. *//*PhD Candidate, University of Mauritius)*/
 /*Director cum Freelance Consultant*/
 /*Soft Sustainable Services (Mauritius)*/
 /*Research and Consultancy*/

 Website: http://sustain-ability.webs.com/


 https://www.linkedin.com/profile/view?id=161468467trk=nav_responsive_tab_profile_pic



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

-- 
Jon Olav Sk�ien
Joint Research Centre - European Commission
Institute for Environment and Sustainability (IES)
Climate Risk Management Unit

Via Fermi 2749, TP 100-01,  I-21027 Ispra (VA), ITALY

jon.sko...@jrc.ec.europa.eu
Tel:  +39 0332 789205

Disclaimer: Views expressed in this email are those of the individual and do 
not necessarily represent official views of the European Commission.


[[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: krigged map do not show colours

2015-08-05 Thread Anand Sookun
Dear Jon and Roman

Thanks for the reply.

Im attaching the code.

You may be right that the variogram may be problematic but it fitted well
visually.

I think also that the prediction grid was not well created. I wiould be
grateful to have to hints.code how to create a useful grid and also for the
spplot or other alternatives

I can send more info if required.

Cheers

Anand

On Tue, Aug 4, 2015 at 1:39 PM, Jon Skoien jon.sko...@jrc.ec.europa.eu
wrote:

 Hi,

 You have attached some data, but we still dont know exactly what you do
 with the data (do you use the logarithm, how many bins, did you project the
 data set...?). However, having had a quick look using the LatLong
 coordinates (not really recommended), I can see that the variogram from
 this data set is not particularly well defined, and it could well be that
 you fitted a model with pure nugget effect. In that case you will get the
 same prediction everywhere and no color differences.

 Have a look at
  summary(map)
 and particularly the summary of var1.pred.
 You could also plot the variogram of the data together with your model,
 vmf, and see how they fit.

 I am not sure what you mean by not being able to create a prediction grid
 with data included. Do you mean that you want a grid which exactly overlays
 some of the data points? Matching one point should not be difficult, 2 and
 3 should be possible, but you might get some problems with precision (FAQ
 7.31).

 Best wishes,
 Jon




 On 8/3/2015 5:30 PM, Anand Sookun wrote:

 Hi

 Thank you Roman for your kind response.

 The data is as attached which is part of the whole dataset.

 My other problem is that im not able to create an appropriate prediction
 grid with some data included.

 The codes which failed to show colour ramps are

 map - krige(logcarbseq ~ 1, locations = carbon_seq, newdata = map,model =
 vmf)
 str(map)
 print(spplot(map, var1.pred, asp=1, col.regions=bpy.colors(64),main=OK
 prediction, carbon))
 print(spplot(map, var1.var,col.regions=cm.colors(64),asp=1, main=OK
 prediction variance, carbon))

 I look forward to hopefully get some solutions.

 Thanks again and warm regards

 Anand

 On Mon, Aug 3, 2015 at 4:09 PM, Roman Luštrik roman.lust...@gmail.com
 wrote:

 What is the variability of the plotted variable?

 Cheers,
 Roman

 On Sun, Aug 2, 2015 at 11:03 AM, Anand Sookun  asoo...@gmail.com
 asoo...@gmail.com wrote:

 Hi

 I have kriged my data but the map shows uniform colours - no gradual
 contour colour plot on map

 code: print(spplot(k40, var1.pred, asp=1,
 col.regions=bpy.colors(64),main=OK prediction, log-ppm Zn))

 thnaks for any help

 Anand Sookun
 --
 ---
 *Anand Sookun (**MPhil. **PhD Candidate, University of Mauritius)*
 *Director cum Freelance Consultant*
 *Soft Sustainable Services (Mauritius)*
 *Research and Consultancy*

 Website: http://sustain-ability.webs.com/



 https://www.linkedin.com/profile/view?id=161468467trk=nav_responsive_tab_profile_pic

 [[alternative HTML version deleted]]

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




 --
 In God we trust, all others bring data.




 --
 ---
 *Anand Sookun (**MPhil. **PhD Candidate, University of Mauritius)*
 *Director cum Freelance Consultant*
 *Soft Sustainable Services (Mauritius)*
 *Research and Consultancy*

 Website:  http://sustain-ability.webs.com/
 http://sustain-ability.webs.com/



 https://www.linkedin.com/profile/view?id=161468467trk=nav_responsive_tab_profile_pic
 https://www.linkedin.com/profile/view?id=161468467trk=nav_responsive_tab_profile_pic



 ___
 R-sig-Geo mailing 
 listR-sig-Geo@r-project.orghttps://stat.ethz.ch/mailman/listinfo/r-sig-geo


 --
 Jon Olav Skøien
 Joint Research Centre - European Commission
 Institute for Environment and Sustainability (IES)
 Climate Risk Management Unit

 Via Fermi 2749, TP 100-01,  I-21027 Ispra (VA), ITALY
 jon.sko...@jrc.ec.europa.eu
 Tel:  +39 0332 789205

 Disclaimer: Views expressed in this email are those of the individual and do 
 not necessarily represent official views of the European Commission.




-- 
---
*Anand Sookun (**MPhil. **PhD Candidate, University of Mauritius)*
*Director cum Freelance Consultant*
*Soft Sustainable Services (Mauritius)*
*Research and Consultancy*

Website: http://sustain-ability.webs.com/


https://www.linkedin.com/profile/view?id=161468467trk=nav_responsive_tab_profile_pic


To sig geoAug2015.R
Description: Binary data


vca_raster.grd
Description: Binary data
___
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: krigged map do not show colours

2015-08-05 Thread Roman Luštrik
Unfortunately we don't have access to all the variables you use in `krige`
call. Consider making a reproducible example.

Cheers,
Roman


On Mon, Aug 3, 2015 at 5:30 PM, Anand Sookun asoo...@gmail.com wrote:

 Hi

 Thank you Roman for your kind response.

 The data is as attached which is part of the whole dataset.

 My other problem is that im not able to create an appropriate prediction
 grid with some data included.

 The codes which failed to show colour ramps are

 map - krige(logcarbseq ~ 1, locations = carbon_seq, newdata = map,model =
 vmf)
 str(map)
 print(spplot(map, var1.pred, asp=1, col.regions=bpy.colors(64),main=OK
 prediction, carbon))
 print(spplot(map, var1.var,col.regions=cm.colors(64),asp=1, main=OK
 prediction variance, carbon))

 I look forward to hopefully get some solutions.

 Thanks again and warm regards

 Anand

 On Mon, Aug 3, 2015 at 4:09 PM, Roman Luštrik roman.lust...@gmail.com
 wrote:

 What is the variability of the plotted variable?

 Cheers,
 Roman

 On Sun, Aug 2, 2015 at 11:03 AM, Anand Sookun asoo...@gmail.com wrote:

 Hi

 I have kriged my data but the map shows uniform colours - no gradual
 contour colour plot on map

 code: print(spplot(k40, var1.pred, asp=1,
 col.regions=bpy.colors(64),main=OK prediction, log-ppm Zn))

 thnaks for any help

 Anand Sookun
 --
 ---
 *Anand Sookun (**MPhil. **PhD Candidate, University of Mauritius)*
 *Director cum Freelance Consultant*
 *Soft Sustainable Services (Mauritius)*
 *Research and Consultancy*

 Website: http://sustain-ability.webs.com/



 https://www.linkedin.com/profile/view?id=161468467trk=nav_responsive_tab_profile_pic

 [[alternative HTML version deleted]]

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




 --
 In God we trust, all others bring data.




 --
 ---
 *Anand Sookun (**MPhil. **PhD Candidate, University of Mauritius)*
 *Director cum Freelance Consultant*
 *Soft Sustainable Services (Mauritius)*
 *Research and Consultancy*

 Website: http://sustain-ability.webs.com/



 https://www.linkedin.com/profile/view?id=161468467trk=nav_responsive_tab_profile_pic




-- 
In God we trust, all others bring data.

[[alternative HTML version deleted]]

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


  1   2   3   >