I try to make a map with the leaflet package on Rstudio.
I try many examples and self options and they all work properly.
But I would like to use a shape file I have at work.
It work with all the software (QGIS, R spplot etc.) but when I use the shape file in leaflet it dosen't work, a blue line appear on the top of the map.
Here is the code i use :
dat<-readOGR(dsn="shape/Shape ER 2015", layer=filename,encoding='UTF-8')
leaflet(dat)%>%addTiles()%>%
addPolgons(data=dat, weight=2)
Here is the result with the code :
and here is the map obtained with spplot :
spplot(dat, zcol=1, col.regions="gray", col="blue")
I have used the same file with http://leaflet.calvinmetcalf.com/ to see if the issue come from my data. But it appear that it come from readOGR
I put here some informations of the SpatialPolygonDataframe
str(dat#polygons[[1]],2)
Formal class 'Polygons' [package "sp"] with 5 slots
..# Polygons :List of 1
..# plotOrder: int 1
..# labpt : num [1:2] 953652 6808716
..# ID : chr "0"
..# area : num 4.32e+10
str(dat#polygons[[1]]#Polygons[[1]],2)
Formal class 'Polygon' [package "sp"] with 5 slots
..# labpt : num [1:2] 953652 6808716
..# area : num 4.32e+10
..# hole : logi FALSE
..# ringDir: int 1
..# coords : num [1:1063, 1:2] 940343 939824 936328 933274 933649 ...
head(dat#polygons[[1]]#Polygons[[1]]#coords)
[,1] [,2]
[1,] 940343 6611180
[2,] 939824 6610705
[3,] 936328 6613788
[4,] 933274 6616467
[5,] 933649 6617058
[6,] 934305 6617147
Hope it's clear, thank you in advance.
You most likely need to transform your projection.
Try:
PRO <- sp::CRS('+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0')
DAT <- sp::spTransform(dat,PRO)
Related
I am working with git2r and want to create some basic statistics about the project's activity.
git2r returns all commits as a list of S4 objects. Below I'm showing the structure of the first object:
> library(git2r)
> repo <- repository('/Users/swain/Dropbox/projects/from-github/brakeman')
> last3 <- commits(repo, n=3)
> str(last3)
List of 3
$ :Formal class 'git_commit' [package "git2r"] with 6 slots
.. ..# sha : chr "f7746c21846d895bd90632df5a2366381ced77d9"
.. ..# author :Formal class 'git_signature' [package "git2r"] with 3 slots
.. .. .. ..# name : chr "Justin"
.. .. .. ..# email: chr "presidentbeef#users.noreply.github.com"
.. .. .. ..# when :Formal class 'git_time' [package "git2r"] with 2 slots
.. .. .. .. .. ..# time : num 1.5e+09
.. .. .. .. .. ..# offset: num -420
.. ..# committer:Formal class 'git_signature' [package "git2r"] with 3 slots
.. .. .. ..# name : chr "GitHub"
.. .. .. ..# email: chr "noreply#github.com"
.. .. .. ..# when :Formal class 'git_time' [package "git2r"] with 2 slots
.. .. .. .. .. ..# time : num 1.5e+09
.. .. .. .. .. ..# offset: num -420
.. ..# summary : chr "Merge pull request #1056 from presidentbeef/hash_access_interpolation_performance_improvements"
.. ..# message : chr "Merge pull request #1056 from presidentbeef/hash_access_interpolation_performance_improvements\n\nHash access i"| __truncated__
.. ..# repo :Formal class 'git_repository' [package "git2r"] with 1 slot
.. .. .. ..# path: chr "/Users/swain/Dropbox/projects/from-github/brakeman"
I have searched high and low for a way to extract one slot from all objects into a list. For example, for all the S4 objects in the list last3 I want to pull author into this new list. Note that there's nesting of objects here, so I may want to make a list from something on an object that's in a slot of the top object.
Ultimately I want to start creating plots and summaries of the various fields. For example, a bar chart of commits by day of the week; box plots of the message length by committer; things like that. Is converting slots to lists or vectors the wrong way to go about it? (edit: s/histogram/bar chart/, doh)
Here's a tidyverse solution to what you're trying to achieve. Jenny Bryan has a nice set of introductory documents on how to use purrr (and other packages) for this sort of task: https://jennybc.github.io/purrr-tutorial/.
library(git2r)
library(dplyr)
library(ggplot2)
library(purrr)
library(lubridate)
options(stringsAsFactors = FALSE)
repo <- repository("/git-repos/brakeman/")
# Get relevant bits out of the list
analysis_df <-
repo %>%
commits(n = 50) %>%
map_df(
~ data.frame(
name = .#author#name,
date = .#author#when#time %>% as.POSIXct(origin="1970-01-01"),
message = .#message
)
)
# A histogram of commits by day of the week;
analysis_df %>%
mutate(weekday = weekdays(date)) %>%
group_by(weekday) %>%
tally() %>%
ggplot(aes(x = weekday, y = n)) +
geom_bar(stat = "identity")
# box plots of the message length by committer
analysis_df %>%
mutate(message_length = nchar(message)) %>%
group_by(name) %>%
summarise(mean_message_length = mean(message_length)) %>%
ggplot(aes(x = name, y = mean_message_length)) +
geom_bar(stat = "identity")
How about
lapply(last3,function(x) data.frame(author = x#author#name, email = x#author#email))
I have n matrices of which I am trying to apply nearPD()from the Matrixpackage.
I have done this using the following code:
A<-lapply(b, nearPD)
where b is the list of n matrices.
I now would like to convert the list A into matrices. For an individual matrix I would use the following code:
A<-matrix(runif(n*n),ncol = n)
PD_mat_A<-nearPD(A)
B<-as.matrix(PD_mat_A$mat)
But I am trying to do this with a list. I have tried the following code but it doesn't seem to work:
d<-lapply(c, as.matrix($mat))
Any help would be appreciated. Thank you.
Here is a code so you can try and reproduce this:
n<-10
generate<-function (n){
matrix(runif(10*10),ncol = 10)
}
b<-lapply(1:n, generate)
Here is the simplest method using as.matrix as noted by #nicola in the comments below and (a version using apply) by #cimentadaj in the comments above:
d <- lapply(A, function(i) as.matrix(i$mat))
My original answer, exploiting the nearPD data structure was
With a little fiddling with the nearPD object type, here is an extraction method:
d <- lapply(A, function(i) matrix(i$mat#x, ncol=i$mat#Dim[2]))
Below is some commentary on how I arrived at my answer.
This object is fairly complicated as str(A[[1]]) returns
List of 7
$ mat :Formal class 'dpoMatrix' [package "Matrix"] with 5 slots
.. ..# x : num [1:100] 0.652 0.477 0.447 0.464 0.568 ...
.. ..# Dim : int [1:2] 10 10
.. ..# Dimnames:List of 2
.. .. ..$ : NULL
.. .. ..$ : NULL
.. ..# uplo : chr "U"
.. ..# factors : list()
$ eigenvalues: num [1:10] 4.817 0.858 0.603 0.214 0.15 ...
$ corr : logi FALSE
$ normF : num 1.63
$ iterations : num 2
$ rel.tol : num 0
$ converged : logi TRUE
- attr(*, "class")= chr "nearPD"
You are interested in the "mat" which is accessed by $mat. The # symbols show that "mat" is an s4 object and its components are accessed using #. The components of interest are "x", the matrix content, and "Dim" the dimension of the matrix. The code above puts this information together to extract the matrices from the list of "nearPD" objects.
Below is a brief explanation of why as.matrix works in this case. Note the matrix inside a nearPD object is not a matrix:
is.matrix(A[[1]]$mat)
[1] FALSE
However, it is a "Matrix":
class(A[[1]]$mat)
[1] "dpoMatrix"
attr(,"package")
[1] "Matrix"
From the note in the help file, help("as.matrix,Matrix-method"),
Loading the Matrix namespace “overloads” as.matrix and as.array in the base namespace by the equivalent of function(x) as(x, "matrix"). Consequently, as.matrix(m) or as.array(m) will properly work when m inherits from the "Matrix" class.
So, the Matrix package is taking care of the as.matrix conversion "under the hood."
I am running a simulation and need to refer to a matrix of parameters from a large object. Here is a snippet of the object structure itself:
Formal class 'mi' [package "mi"] with 3 slots
..# call : language .local(y = y, n.chains = ..2, max.minutes = 20000)
..# data :List of 100
.. ..$ chain:1 :'data.frame': 10000 obs. of 76 variables:
Formal class 'missing_data.frame' [package "mi"] with 17 slots
.. .. .. ..# .Data : list()
.. .. .. ..# variables :List of 76
.. .. .. .. ..$ y.obs.tx:Formal class 'binary' [package "mi"] with 27 slots
...
The parameter list I need can be referenced by:
mi.control.i#data$'chain:1'#variables$y.obs.tx#parameters[30,]
Since this is a simulation, I would like to grab the parameters from each chain and join them together in a matrix. I have this:
tf <- vector("list", numberofchains)
for (j in 1:numberofchains){
s <- paste("'chain:",j,"'" ,sep="")
tf[[j]] = mi.control.i#data$s#variables$y.obs.tx#parameters[30,]
}
Within the loop, however, the reference to the object (tf[[j]]) does not work. I get an error that reads
Error: trying to get slot "variables" from an object of a basic class
("NULL") with no slots
Any ideas?
I'm using ggmap library in R. I'm trying to download a rectangular map with it, but I know it'll give me a square. I only need the bounding box of the returned square.
library(ggmap)
map <- get_map(c(-65.7,-3.1,-64.4,-2.3),maptype="satellite",filename="map.png")
str(map)
chr [1:1280, 1:1280] "#294829" "#294829" "#2D512D" "#264425" ...
- attr(*, "class")= chr [1:2] "ggmap" "raster"
- attr(*, "bb")='data.frame': 1 obs. of 4 variables:
..$ ll.lat: num -3.14
..$ ll.lon: num -65.5
..$ ur.lat: num -2.26
..$ ur.lon: num -64.6
Object map have two classes "ggmap" and "raster". I can't use # or $ in it. How then can I access the ll.lat and other attributes from "bb" sub-object?
You can do this:
> attr(map, "bb")
ll.lat ll.lon ur.lat ur.lon
1 -3.139567 -65.48877 -2.261646 -64.60986
I've imported some GPS points from my Sports watch into R:
library(plotKML)
route <- readGPX("Move_Cycling.gpx")
str(route)
The data looks like this:
List of 5
$ metadata : NULL
$ bounds : NULL
$ waypoints: NULL
$ tracks :List of 1
..$ :List of 1
.. ..$ Move:'data.frame': 677 obs. of 5 variables:
.. .. ..$ lon : num [1:677] -3.8 -3.8 -3.8 -3.8 -3.8 ...
.. .. ..$ lat : num [1:677] 52.1 52.1 52.1 52.1 52.1 ...
.. .. ..$ ele : chr [1:677] "152" "151" "153" "153" ...
.. .. ..$ time : chr [1:677] "2014-06-08T09:17:08.050Z" "2014-06-08T09:17:18.680Z" "2014-06-08T09:17:23.680Z" "2014-06-08T09:17:29.680Z" ...
.. .. ..$ extensions: chr [1:677] "7627.7999992370605141521101800" "7427.6000003814697141511.7000000476837210180.8490009442642210" "9127.523.13003521531.7000000476837210181.799999952316280" "10027.534.96003841534.1999998092651410181.88300029210510" ...
$ routes : NULL
I've managed to transform to get the data points into a SpatialPointsDataFrame and to plot it over Google Earth with:
SPDF <- SpatialPointsDataFrame(coords=route$tracks[[1]]$Move[1:2],
data=route$tracks[[1]]$Move[1:2],
proj4string = CRS("+init=epsg:4326"))
plotKML(SPDF)
What I really want is the cycling track, i.e. a SpatialLinesDataFrame, but I can't work out how to set the ID field correctly to match the SpatialLines object with the data.
This is how far I've got:
tmp <- Line(coords=route$tracks[[1]]$Move[1:2])
tmp2 <- Lines(list(tmp), ID=c("coord"))
tmp3 <- SpatialLines(list(tmp2), proj4string = CRS("+init=epsg:4326"))
# result should be something like,
# but the ID of tmp3 and data don't match at the moment
SPDF <- SpatialLinesDataFrame(tmp3, data)
You can read the GPX file straight into a SpatialLinesDataFrame object with readOGR from the rgdal package. A GPX file can contain tracks, waypoints, etc and these are seen by OGR as layers in the file. So simply:
> track = readOGR("myfile.gpx","tracks")
> plot(track)
should work. You should see lines.
In your last line you've not said what your data is, but it needs to be a data frame with one row per track if you are trying to construct a SpatialLinesDataFrame from some SpatialLines and a data frame, and you can tell it not to bother matching the IDs because you don't actually have any real per-track data you are merging. So:
> SPDF = SpatialLinesDataFrame(tmp3, data.frame(who="me"),match=FALSE)
> plot(SPDF)
But if you use readOGR you don't need to go through all that. It will also read in a bit of per-track metadata from the GPX file.
Happy cycling!
As an update, here's my final solution
library(rgdal)
library(plotKML)
track <- readOGR("Move_Cycling.gpx","tracks")
plotKML(track, colour='red', width=2, labels="Cwm Rhaeadr Trail")