• Artículos
  • Documentos
    • Libro de Energía Solar Fotovoltaica
  • Omnia sunt Communia!

Omnia sunt Communia!

~ Sobre software, documentación y ciencia libres

Omnia sunt Communia!

Archivos de etiqueta: R

Mapping Flows in R … with data.table and lattice

14 martes Abr 2015

Posted by Oscar Perpiñán Lamigueiro in R-english, visualization

≈ 6 comentarios

Etiquetas

data.table, lattice, R, spatial data

Some days ago James Cheshire published the post Mapping Flows in R. I have implemented an alternative (faster) version using data.table to read and join the datasets (and lattice to display the results). If you are new to data.table you should read this wiki and this cheatsheet.

This is the code:


### DATA SECTION
library(data.table)
## Read data with 'data.table::fread'
input <- fread("wu03ew_v1.csv", select = 1:3)
setnames(input, 1:3, new = c("origin", "destination","total"))
## Coordinates
centroids <- fread("msoa_popweightedcentroids.csv")
## 'Code' is the key to be used in the joins
setkey(centroids, Code)
## Key of centroids matches `origin` in `input`
origin <- centroids[input[,.(origin, total)]]
setnames(origin, c('East', 'North'), c('xstart', 'ystart'))
## Key of centroids matches `destination` in `input`
destination <- centroids[input[,.(destination)]]
setnames(destination, c('East', 'North'), c('xend', 'yend'))
## Bind both results
trajects <- cbind(origin, destination)
### GRAPHICS SECTION
library(lattice)
library(classInt)
## Background set to black
myTheme <- simpleTheme()
myTheme$background$col <- 'black'
## Palette and classes
nClasses <- 5
pal <- colorRampPalette(c('gray70', 'white'))(nClasses)
classes <- classIntervals(trajects[total > 10, total],
n = nClasses, style = 'quantile')
classes <- findCols(classes)
xyplot(North ~ East, data = centroids,
pch = '.', col = 'lightgray',
aspect = 'iso',
par.settings = myTheme,
panel = function(…){
## panel.xyplot displays the 'centroids'
panel.xyplot(…)
## panel.segments displays the lines using a `data.table`
## query.
trajects[total > 10,
panel.segments(xstart, ystart, xend, yend,
col = pal[classes],
alpha = 0.05, lwd = 0.3)
]
})

view raw

mappingFlows.R

hosted with ❤ by GitHub

This is the result:

london

Related articles
  • Spatial data visualization with R
  • Maps with R (I)
  • Maps with R (II)
  • Maps with R (III)
  • Stamen maps with spplot
Anuncio publicitario

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...

R para Datos Espaciales

23 domingo Nov 2014

Posted by Oscar Perpiñán Lamigueiro in R-castellano

≈ Comentarios desactivados en R para Datos Espaciales

Etiquetas

datos espaciales, geoestadística, R, raster, UPM, visualización

Durante este mes de Noviembre he tenido la oportunidad de impartir un curso introductorio de R en el CEIGRAM de la UPM. He utilizado el material que está disponible aquí, que he corregido y mejorado.

Algunos participantes tenían especial interés en conocer las posibilidades que ofrece R para trabajar con datos espaciales. Esta es la información que les he hecho llegar.

La primera fuente de información es la CRAN Tasks View «Analysis of Spatial Data’’ . Hace un resumen exhaustivo de todos los paquetes que sirven para leer y escribir, visualizar, y analizar datos espaciales. También es útil la web http://rspatial.r-forge.r-project.org/, aunque es algo antigua. Por otra parte, existe un libro de referencia, “Applied Spatial Data Analysis with R”, de Bivand, Pebesma y Gómez-Rubio. Todo el código está disponible en su web.

Dentro de los paquetes destacan:

  • sp  es el paquete fundamental para trabajar con datos vectoriales (puntos, líneas y polígonos). Es de los mismos autores que el libro que mencionaba. Es recomendable leer este documento introductorio.
  • raster es el paquete fundamental para trabajar con datos raster (matrices georeferenciadas, típicas en imágenes de satélite y similares). Define funciones para crear, leer, manipular y escribir este tipo de datos. Es recomendable leer este documento introductorio.
  • gstat es el paquete por excelencia para hacer análisis geoestadístico en R. Permite hacer modelado de variogramas, interpolación IDW, kriging ordinario, y kriging con regresión. Se estudia en profundidad en el libro que indicaba antes. Es recomendable este documento de introducción.
  • rgdal es una interface para GDAL. Entre otras cosas, permite transformar proyecciones. Complementa a sp y raster.
  • maptools proporciona funciones para leer y manipular datos tipo “shapefile”. Es un buen complemento para sp.

En cuanto a fuentes de datos tipo espaciales destacaría las siguientes:

  • NASA Earth Observations (NEO). En este repositorio de imágenes hay que seleccionar el formato GeoTiff para poder usarlo con el paquete raster.
  • Natural Earth Data.
  • DIVA-GIS.
  • CM SAF.  Sobre esta fuente publicamos un artículo hace algo más de un año. El código asociado está disponible en este repositorio. Es un recurso útil para ver cómo usar datos raster y vectoriales en R, y cómo usar las funciones de gstat para hacer variogramas y kriging.
  • En esta wiki recopilo fuentes de datos meteorológicos.

Por último, para la visualización de datos espaciales, pueden resultar útil dos recursos que he publicado:

  • El paquete rasterVis, que complementa al paquete raster, para visualización de datos raster. En su web hay varios ejemplos de uso, y hay unos tutoriales publicados por Agustín Lobo.
  • El libro que publiqué hace unos meses, “Displaying Time Series, Spatial, and Space-Time Data with R”. El código y las imágenes principales están disponibles en su web.

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...

meteoForecast 0.43: GFS, NAM, and RAP included

20 lunes Oct 2014

Posted by Oscar Perpiñán Lamigueiro in R-english, R-project, Software

≈ Comentarios desactivados en meteoForecast 0.43: GFS, NAM, and RAP included

Etiquetas

forecast, meteorological data, NWP, R, WRF

Some months ago I published the meteoForecast package, with functions to download data from the Meteogalicia and OpenMeteo NWP-WRF services. Now there is a new version available at CRAN. This update includes a bunch of bug fixes, some additional features, and three new services: GFS, NAM, and RAP.

servicesMap

You will find detailed information and examples here.

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...

meteoForecast, a package to obtain NWP-WRF forecasts in R

08 martes Jul 2014

Posted by Oscar Perpiñán Lamigueiro in R-english, Software

≈ 13 comentarios

Etiquetas

forecast, NWP, R, raster, spatial, WRF

wrfDaysThe Weather Research and Forecasting (WRF) Model is a numerical weather prediction (NWP) system. NWP refers to the simulation and prediction of the atmosphere with a computer model, and WRF is a set of software for this.

meteoForecast is a new R package that implements functions to download data from the Meteogalicia and OpenMeteo NWP-WRF services using the NetCDF Subset Service.

Read this introduction for additional information and examples.

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...

Displaying time series, spatial, and space-time data with R is available for pre-order

10 lunes Mar 2014

Posted by Oscar Perpiñán Lamigueiro in latex, R-english, visualization

≈ 10 comentarios

Etiquetas

code, emacs, latex, listings, memoir, orgmode, R, reproducible research, visualization

Two years ago, motivated by a proposal from John Kimmel, Executive Editor at Chapman & Hall/CRC Press, I started working in a book, “Displaying time series, spatial, and space-time data with R”. This book presents methods and R code for producing high-quality graphics of time series, spatial, and space-time data.

9781466565203.jpg

The book is already available for pre-order at CRC Press and Amazon. It will be published on April 4th, 2014. Along with the main graphics from the text, the book website offers access to the datasets used in the examples as well as the full R code.

I have spent a large amount of time and effort in this project but, now that it is finished, I can say it has been worthwhile. One of the challenges was to produce a fully reproducible book including hundreds of code chunks and graphics, and survive after several rounds of peer-reviewing. Among the tools that can create reproducible documents with R, I decided to use these gems of open-source software:

  • GNU Emacs as development environment.
  • R (of course!) with Emacs Speaks Statistics.
  • org-mode for authoring text and code.
  • LaTeX with AUCTeX to produce the final document.

If you are interested in the technical details read about writing a book with Emacs and friends.

Comparte / Share

  • Correo electrónico
  • Imprimir
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Más
  • Tumblr
  • Reddit

Me gusta esto:

Me gusta Cargando...
← Entradas anteriores

Omnia sunt communia!

“As we enjoy great advantages from the inventions of others, we should be glad of an opportunity to serve others by any invention of ours, and this we should do freely and generously”

RSS Feed RSS - Entradas

Introduce tu correo electrónico para suscribirte a este blog y recibir avisos de nuevas entradas.

Únete a otros 91 suscriptores

Posts Más Vistos

  • Libro de Energía Solar Fotovoltaica
  • Vector fields with streamlines
View Oscar Perpiñán Lamigueiro's profile on LinkedIn
profile for Oscar Perpiñán on Stack Exchange, a network of free, community-driven Q&A sites
Citations for Oscar Perpinan

@oscarperpinan

Mis tuits

Enlaces

  • Displaying time series, spatial and space-time data with R
  • Introducción a R

Top Clicks

  • oscarperpinan.github.com/…
  • r-bloggers.com/2023/05/3d…

Etiquetas

actuar anarquía autocontención ayuda mutua bloch ciencia circuitos eléctricos común cooperación CRAN creative commons data data.table data analysis ecología emacs Energía energía solar fotovoltaica entropía EOI esperanza exergía forecast fotovoltaica galeano github GNU General Public License información investigación jorge riechmann kropotkin latex lattice lewis mumford libro lyx map maps memoir meteorological data movimientos sociales nestoria nicolas georgescu roegen NWP open data openstreetmap orgmode pensar photovoltaics pobreza R R-project radiación solar raster rasterVis reproducible research siar small multiples software libre solar solar radiation sp spatial spatial data spplot tecnología time series trellis tufte uned utopía Vector field visualización visualization WRF

RSS R-bloggers

  • Simulating confounders, colliders and mediators by @ellis2013nz
  • Introduction to Mixed-effects Models in R workshop
  • Learn to ‘Make an outstanding Shiny App’ with us
  • Sorting, Ordering, and Ranking: Unraveling R’s Powerful Functions
  • Galton and Watson voluntarily skipping some generations
  • {attachment} v0.4.0: Breaking changes and configuration file for a better experience
  • Sharing the Big Book of R upgrade proposal
  • The do.call() function in R: Unlocking Efficiency and Flexibility
  • Version 1.0.0 of NIMBLE released, providing automatic differentiation, Laplace approximation, and HMC sampling
  • Checking normality in R

RSS dataanalytics

  • Se ha producido un error; es probable que la fuente esté fuera de servicio. Vuelve a intentarlo más tarde.

RSS Solar Energy (Elsevier)

  • Se ha producido un error; es probable que la fuente esté fuera de servicio. Vuelve a intentarlo más tarde.

RSS Progress in Photovoltaics

  • Se ha producido un error; es probable que la fuente esté fuera de servicio. Vuelve a intentarlo más tarde.

RSS Madridmasd

  • Cambio Climático, Gobiernos y Empresas; Casi todas sus promesas son mentira
  • Proyectos estratégicos para la recuperación y transformación económica (PERTE)
  • ¿En quién confiar? Debate sobre IA, ética y comunicación en el congreso de medios de comunicación
  • La Civilización perdida bajo los suelos y vegetación de Latinoamérica.
  • IMDEA Software e IMDEA Networks trabajan para desplegar en la Comunidad de Madrid “MadQCI”: la mayor red cuántica de Europa
  • Etnografía y Paleoecología de los Paisajes Precolombinos: El Papel del Fuego en las Culturas Aborígenes del SO de América del Norte (tribus Karuk y Yurok)
  • Homenaje a Manuel Espadas Burgos
  • Super Mario World
  • Taller doctoral en Historia de las Relaciones Internacionales 2023 en la Universidad de Padua
  • Directiva Europea de Protección de Suelos: Dos décadas de “vistas” y “consideraciones” y otras desconsideraciones
Licencia Creative Commons
Salvo indicación en contra todos los contenidos están publicados por Oscar Perpiñán Lamigueiro bajo una Licencia Creative Commons Reconocimiento-No Comercial-Compartir Igual 3.0 Unported.

Blog de WordPress.com.

Privacidad y cookies: este sitio utiliza cookies. Al continuar utilizando esta web, aceptas su uso.
Para obtener más información, incluido cómo controlar las cookies, consulta aquí: Política de cookies
  • Seguir Siguiendo
    • Omnia sunt Communia!
    • Únete a 91 seguidores más
    • ¿Ya tienes una cuenta de WordPress.com? Inicia sesión.
    • Omnia sunt Communia!
    • Personalizar
    • Seguir Siguiendo
    • Regístrate
    • Iniciar sesión
    • Denunciar este contenido
    • Ver sitio web en el Lector
    • Gestionar las suscripciones
    • Contraer esta barra
 

Cargando comentarios...
 

    A %d blogueros les gusta esto: