楼主: ReneeBK
2147 8

[休闲其它] 【独家发布】Displaying Time Series, Spatial, and Space-Time Data with R [推广有奖]

  • 1关注
  • 62粉丝

VIP

已卖:4900份资源

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49655 个
通用积分
55.9937
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57805 点
帖子
4005
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

楼主
ReneeBK 发表于 2014-11-21 04:08:30 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币

Displaying Time Series, Spatial, and Space-Time Data with R


https://github.com/oscarperpinan/spacetime-vis
http://www.crcpress.com/product/isbn/9781466565203
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Time Series displaying Display Playing Spatial Series

本帖被以下文库推荐

沙发
ReneeBK 发表于 2014-11-21 04:11:35
  1. airStations <- read.csv2('data/airStations.csv')
  2. coordinates(airStations) <- ~ long + lat
  3. ## Geographical projection
  4. -proj4string(airStations) <- CRS("+proj=longlat +ellps=WGS84")
  5. +proj4string(airStations) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")

  6. ## Measurements data
  7. airQuality <- read.csv2('data/airQuality.csv')
复制代码
  1. library(rgdal)
  2. writeOGR(NO2sp, 'data/NO2.geojson', 'NO2sp', driver='GeoJSON')

  3. +library(rgdal)
  4. +writeOGR(NO2sp, dsn='NO2_mean.kml', layer='mean', driver='KML')
  5. +
  6. +library(plotKML)
  7. +plotKML(NO2sp["mean"], points_names=NO2sp$codEst)
  8. +
  9. ##################################################################
  10. ## Additional information with tooltips and hyperlinks
  11. ##################################################################
复制代码

藤椅
ReneeBK 发表于 2014-11-21 04:14:08
  1. ##################################################################
  2. ## Source code for the book: "Displaying time series, spatial and
  3. ## space-time data with R"

  4. ## Copyright (C) 2013-2012 Oscar Perpiñán Lamigueiro

  5. ## This program is free software you can redistribute it and/or modify
  6. ## it under the terms of the GNU General Public License as published
  7. ## by the Free Software Foundation; either version 2 of the License,
  8. ## or (at your option) any later version.

  9. ## This program is distributed in the hope that it will be useful, but
  10. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  12. ## General Public License for more details.

  13. ## You should have received a copy of the GNU General Public License
  14. ## along with this program; if not, write to the Free Software
  15. ## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  16. ## 02111-1307, USA.
  17. ####################################################################

  18. ##################################################################
  19. ## Initial configuration
  20. ##################################################################
  21. ## Clone or download the repository and set the working directory
  22. ## with setwd to the folder where the repository is located.

  23. ##################################################################
  24. ## Air Quality in Madrid
  25. ##################################################################

  26. ## codeStations.csv is extracted from the document
  27. ## http://www.mambiente.munimadrid.es/opencms/export/sites/default/calaire/Anexos/INTPHORA-DIA.pdf,
  28. ## table of page 3.

  29. codEstaciones <- read.csv2('data/codeStations.csv')
  30. codURL <- as.numeric(substr(codEstaciones$Codigo, 7, 8))

  31. ## The information of each measuring station is available at its own webpage, defined by codURL
  32. URLs <- paste('http://www.mambiente.munimadrid.es/opencms/opencms/calaire/contenidos/estaciones/estacion', codURL, '.html', sep='')

  33. ##################################################################
  34. ## Data arrangement
  35. ##################################################################

  36. library(XML)
  37. library(sp)

  38. ## Access each webpage, retrieve tables and extract long/lat data
  39. coords <- lapply(URLs, function(est){
  40.   tables <- readHTMLTable(est)
  41.   location <- tables[[2]]
  42.   ## Clean the table content and convert to dms format
  43.   ub2dms <- function(x){
  44.     ch <- as.character(x)
  45.     ch <- sub(',', '.', ch)
  46.     ch <- sub('O', 'W', ch) ## Some stations use "O" instead of "W"
  47.     as.numeric(char2dms(ch, "o", "'", "'' "))
  48.   }
  49.   long <- ub2dms(location[2,1])
  50.   lat <- ub2dms(location[2,2])
  51.   alt <- as.numeric(sub(' m.', '', location[2, 3]))

  52.   coords <- data.frame(long=long, lat=lat, alt=alt)

  53.   coords
  54. })

  55. airStations <- cbind(codEstaciones, do.call(rbind, coords))

  56. ## The longitude of "El Pardo" station is wrong (positive instead of negative)
  57. airStations$long[22] <- -airStations$long[22]

  58. write.csv2(airStations, file='data/airStations.csv')

  59. ## Fill in the form at
  60. ## http://www.mambiente.munimadrid.es/opencms/opencms/calaire/consulta/descarga.html
  61. ## to receive the Diarios11.zip file.
  62. unzip('data/Diarios11.zip')
  63. rawData <- readLines('data/Datos11.txt')
  64. ## This loop reads each line and extracts fields as defined by the
  65. ## INTPHORA file:
  66. ## http://www.mambiente.munimadrid.es/opencms/export/sites/default/calaire/Anexos/INTPHORA-DIA.pdf
  67. datos11 <- lapply(rawData, function(x){
  68.   codEst <- substr(x, 1, 8)
  69.   codParam <- substr(x, 9, 10)
  70.   codTec <- substr(x, 11, 12)
  71.   codPeriod <- substr(x, 13, 14)
  72.   month <- substr(x, 17, 18)
  73.   dat <- substr(x, 19, nchar(x))
  74.   ## "N" used for impossible days (31st April)
  75.   idxN <- gregexpr('N', dat)[[1]]
  76.   if (idxN==-1) idxN <- numeric(0)
  77.   nZeroDays <- length(idxN)
  78.   day <- seq(1, 31-nZeroDays)
  79.   ## Substitute V and N with ";" to split data from different days
  80.   dat <- gsub('[VN]+', ';', dat)
  81.   dat <- as.numeric(strsplit(dat, ';')[[1]])
  82.   ## Only data from valid days
  83.   dat <- dat[day]
  84.   res <- data.frame(codEst, codParam, ##codTec, codPeriod,
  85.                     month, day, year=2011,
  86.                     dat)
  87.   })
  88. datos11 <- do.call(rbind, datos11)
  89. write.csv2(datos11, 'data/airQuality.csv')

  90. ##################################################################
  91. ## Combine data and spatial locations
  92. ##################################################################

  93. library(sp)

  94. ## Spatial location of stations
  95. airStations <- read.csv2('data/airStations.csv')
  96. coordinates(airStations) <- ~ long + lat
  97. ## Geographical projection
  98. proj4string(airStations) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")

  99. ## Measurements data
  100. airQuality <- read.csv2('data/airQuality.csv')
  101. ## Only interested in NO2
  102. NO2 <- airQuality[airQuality$codParam==8, ]

  103. NO2agg <- aggregate(dat ~ codEst, data=NO2,
  104.                     FUN = function(x) {
  105.                         c(mean=signif(mean(x), 3),
  106.                           median=median(x),
  107.                           sd=signif(sd(x), 3))
  108.                         })
  109. NO2agg <- do.call(cbind, NO2agg)
  110. NO2agg <- as.data.frame(NO2agg)

  111. library(maptools)
  112. ## Link aggregated data with stations to obtain a SpatialPointsDataFrame.
  113. ## Codigo and codEst are the stations codes
  114. idxNO2 <- match(airStations$Codigo, NO2agg$codEst)
  115. NO2sp <- spCbind(airStations[, c('Nombre', 'alt')], NO2agg[idxNO2, ])
  116. save(NO2sp, file='data/NO2sp.RData')

  117. ##################################################################
  118. ## Spanish General Elections
  119. ##################################################################

  120. dat2011 <- read.csv('data/GeneralSpanishElections2011.gz')

  121. census <- dat2011$Total.censo.electoral
  122. validVotes <- dat2011$Votos.válidos
  123. ## Election results per political party and municipality
  124. votesData <- dat2011[, 12:1023]
  125. ## Abstention as an additional party
  126. votesData$ABS <- census - validVotes
  127. ## Winner party at each municipality
  128. whichMax <- apply(votesData,  1, function(x)names(votesData)[which.max(x)])
  129. ## Results of the winner party at each municipality
  130. Max <- apply(votesData, 1, max)
  131. ## OTH for everything but PP, PSOE and ABS
  132. whichMax[!(whichMax %in% c('PP',  'PSOE', 'ABS'))] <- 'OTH'
  133. ## Percentage of votes with the electoral census
  134. pcMax <- Max/census * 100

  135. ## Province-Municipality code. sprintf formats a number with leading zeros.
  136. PROVMUN <- with(dat2011, paste(sprintf('%02d', Código.de.Provincia),
  137.                                sprintf('%03d', Código.de.Municipio),
  138.                                sep=""))

  139. votes2011 <- data.frame(PROVMUN, whichMax, Max, pcMax)
  140. write.csv(votes2011, 'data/votes2011.csv', row.names=FALSE)

  141. ##################################################################
  142. ## CM SAF
  143. ##################################################################

  144. library(raster)

  145. tmp <- tempdir()
  146. unzip('data/SISmm2008_CMSAF.zip', exdir=tmp)
  147. filesCMSAF <- dir(tmp, pattern='SISmm')
  148. SISmm <- stack(paste(tmp, filesCMSAF, sep='/'))
  149. ## CM-SAF data is average daily irradiance (W/m2). Multiply by 24
  150. ## hours to obtain daily irradiation (Wh/m2)
  151. SISmm <- SISmm * 24

  152. ## Monthly irradiation: each month by the correspondent number of days
  153. daysMonth <- c(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
  154. SISm <- SISmm * daysMonth / 1000 ## kWh/m2
  155. ## Annual average
  156. SISav <- sum(SISm)/sum(daysMonth)
  157. writeRaster(SISav, file='SISav')

  158. library(raster)
  159. ## http://neo.sci.gsfc.nasa.gov/Search.html?group=64
  160. pop <- raster('875430rgb-167772161.0.FLOAT.TIFF')
  161. ## http://neo.sci.gsfc.nasa.gov/Search.html?group=20
  162. landClass <- raster('241243rgb-167772161.0.TIFF')
复制代码


板凳
ReneeBK 发表于 2014-11-21 04:15:36
  1. ##################################################################
  2. ## Source code for the book: "Displaying time series, spatial and
  3. ## space-time data with R"
  4. ##
  5. ## Copyright (C) 2013-2012 Oscar Perpiñán Lamigueiro
  6. ##
  7. ## This program is free software you can redistribute it and/or modify
  8. ## it under the terms of the GNU General Public License as published
  9. ## by the Free Software Foundation; either version 2 of the License,
  10. ## or (at your option) any later version.
  11. ##
  12. ## This program is distributed in the hope that it will be useful, but
  13. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15. ## General Public License for more details.
  16. ##
  17. ## You should have received a copy of the GNU General Public License
  18. ## along with this program; if not, write to the Free Software
  19. ## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  20. ## 02111-1307, USA.
  21. ####################################################################

  22. ##################################################################
  23. ## Initial configuration
  24. ##################################################################
  25. ## Clone or download the repository and set the working directory
  26. ## with setwd to the folder where the repository is located.

  27. ##################################################################
  28. ## OpenStreetMap with Hill Shade layers
  29. ##################################################################

  30. ##################################################################
  31. ## Retrieving data from OpenStreetMap
  32. ##################################################################

  33. library('osmar')

  34. api <- osmsource_api()
  35. ymax <- 43.7031
  36. ymin <- 43.6181
  37. xmax <- -8.0224
  38. xmin <- -8.0808
  39. box <- corner_bbox(xmin, ymin, xmax, ymax)
  40. cedeira <- get_osm(box, source=api, full=TRUE)

  41. summary(cedeira$nodes)

  42. idxHighways <- find(cedeira, way(tags(k=='highway')))
  43. highways <- subset(cedeira, way_ids=idxHighways)
  44. idxStreets <- find(highways, way(tags(v=='residential')))
  45. idxPrimary <- find(highways, way(tags(v=='primary')))
  46. idxSecondary <- find(highways, way(tags(v=='secondary')))
  47. idxTertiary <- find(highways, way(tags(v=='tertiary')))
  48. idxOther <- find(highways,
  49.                  way(tags(v=='unclassified' |
  50.                           v=='footway' |
  51.                           v=='steps')))

  52. spFromOSM <- function(source, index, type='lines'){
  53.   idx <- find_down(source, index)
  54.   obj <- subset(source, ids=idx)
  55.   objSP <- as_sp(obj, type)
  56.   }

  57. streets <- spFromOSM(cedeira, way(idxStreets))
  58. primary <- spFromOSM(cedeira, way(idxPrimary))
  59. secondary <- spFromOSM(cedeira, way(idxSecondary))
  60. tertiary <- spFromOSM(cedeira, way(idxTertiary))
  61. other <- spFromOSM(cedeira, way(idxOther))

  62. idxPlaces <- find(cedeira, node(tags(k=='name')))
  63. places <- spFromOSM(cedeira, node(idxPlaces), 'points')

  64. nms <- subset(cedeira$nodes$tags, subset=(k=='name'), select=c('id', 'v'))
  65. ord <- match(idxPlaces, nms$id)
  66. nms <- nms[ord,]
  67. places$name <- nms$v[ord]

  68. ## Cedeira town will be printed differently
  69. idxCedeira <- which(nms$v=='Cedeira') ##Main town
  70. cedeiraCoords <- coordinates(places[idxCedeira,])
  71. places <- places[-idxCedeira,]

  72. ##################################################################
  73. ## Hill Shading
  74. ##################################################################

  75. library(raster)
  76. ## Galicia DEM
  77. ## http://ide.unex.es/geonetwork/srv/es/main.search?any=MDE_Galicia
  78. ## http://ide.unex.es:8180/geonetwork/srv/es/resources.get?id=21&fname=dem_gal.7z&access=private

  79. old <- tempdir()
  80. download.file('http://ide.unex.es:8180/geonetwork/srv/es/resources.get?id=21&fname=dem_gal.7z&access=private', 'dem_gal.7z')
  81. unzip('dem_gal.7z')
  82. demGalicia <- raster('dem_gal.asc')
  83. setwd(old)

  84. cedeiraSP <- as_sp(cedeira, 'points')
  85. projCedeira <- projection(cedeiraSP)
  86. ##extCedeira <- bbox(cedeiraSP)
  87. ## or summary(cedeira$nodes)$bbox
  88. extCedeira <- extent(-8.15, -7.95, 43.6, 43.75)
  89. demCedeira <- crop(demGalicia, extCedeira)
  90. projection(demCedeira) <- projCedeira
  91. demCedeira[demCedeira <= 0] <- NA

  92. slope <- terrain(demCedeira, 'slope')
  93. aspect <- terrain(demCedeira, 'aspect')
  94. hsCedeira <- hillShade(slope=slope, aspect=aspect,
  95.                        angle=20, direction=30)

  96. ##################################################################
  97. ## Overlaying layers of information
  98. ##################################################################

  99. pdf(file="figs/cedeiraOsmar.pdf")
  100. library(maptools)
  101. library(latticeExtra)
  102. library(colorspace)
  103. library(rasterVis)

  104. ##Auxiliary function to display the roads. A thicker black line in
  105. ##the background and a thinner one with an appropiate color.
  106. sp.road <- function(line, lwd=5, blwd=7,
  107.                     col='indianred1', bcol='black'){
  108.   sp.lines(line, lwd=blwd, col=bcol)
  109.   sp.lines(line, lwd=lwd, col=col)
  110. }

  111. ## The background color of the panel is set to blue to represent the sea
  112. hsTheme <- modifyList(GrTheme(), list(panel.background=list(col='skyblue3')))
  113. ## DEM with terrain colors and semitransparency
  114. terrainTheme <- modifyList(rasterTheme(region=terrain_hcl(n=15)),
  115.                                 list(regions=list(alpha=0.6)))
  116. ## Hill shade and DEM overlaid
  117. levelplot(hsCedeira, maxpixels=ncell(hsCedeira),
  118.           par.settings=hsTheme, margin=FALSE, colorkey=FALSE) +
  119.   levelplot(demCedeira, maxpixels=ncell(demCedeira),
  120.             par.settings=terrainTheme) +
  121.   ## Roads and places
  122.   layer({
  123.     ## Street and roads
  124.     sp.road(streets, lwd=1, blwd=2, col='white')
  125.     sp.road(other, lwd=2, blwd=3, col='white')
  126.     sp.road(tertiary, lwd=3, blwd=4, col='palegreen')
  127.     sp.road(secondary, lwd=4, blwd=6, col='midnightblue')
  128.     sp.road(primary, col='indianred1')
  129.     ## Places except Cedeira town
  130.     sp.points(places, pch=19, col='black', cex=0.4, alpha=0.8)
  131.     sp.pointLabel(places, labels=places$name,
  132.                       fontfamily = 'Palatino',
  133.                       cex=0.6, col='black')
  134.     ## Cedeira town
  135.     panel.points(cedeiraCoords, pch=18, col='black', cex=1)
  136.     panel.text(cedeiraCoords, labels='Cedeira', pos=2, offset=1)
  137.     })
  138. dev.off()
复制代码


报纸
ReneeBK 发表于 2014-11-21 04:17:49
  1. ##################################################################
  2. ## Source code for the book: "Displaying time series, spatial and
  3. ## space-time data with R"

  4. ## Copyright (C) 2012 Oscar Perpiñán Lamigueiro

  5. ## This program is free software you can redistribute it and/or modify
  6. ## it under the terms of the GNU General Public License as published
  7. ## by the Free Software Foundation; either version 2 of the License,
  8. ## or (at your option) any later version.

  9. ## This program is distributed in the hope that it will be useful, but
  10. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  12. ## General Public License for more details.

  13. ## You should have received a copy of the GNU General Public License
  14. ## along with this program; if not, write to the Free Software
  15. ## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  16. ## 02111-1307, USA.
  17. ####################################################################

  18. ##################################################################
  19. ## SIAR
  20. ##################################################################

  21. ##################################################################
  22. ## Daily data of different meteorological variables
  23. ##################################################################

  24. library(zoo)

  25. aranjuez <- read.zoo("data/aranjuez.gz",
  26.                      index.column = 3, format = "%d/%m/%Y",
  27.                      fileEncoding = 'UTF-16LE',
  28.                      header = TRUE, fill = TRUE,
  29.                      sep = ';', dec = ",", as.is = TRUE)
  30. aranjuez <- aranjuez[, -c(1:4)]

  31. names(aranjuez) <- c('TempAvg', 'TempMax', 'TempMin',
  32.                      'HumidAvg', 'HumidMax',
  33.                      'WindAvg', 'WindMax',
  34.                      'Radiation', 'Rain', 'ET')


  35. summary(aranjuez)

  36. aranjuezClean <- within(as.data.frame(aranjuez),{
  37.   TempMin[TempMin>40] <- NA
  38.   HumidMax[HumidMax>100] <- NA
  39.   WindAvg[WindAvg>10] <- NA
  40.   WindMax[WindMax>10] <- NA
  41. })

  42. aranjuez <- zoo(aranjuezClean, index(aranjuez))

  43. save(aranjuez, file='data/aranjuez.RData')

  44. ##################################################################
  45. ## Solar radiation measurements from different locations
  46. ##################################################################

  47. ##################################################################
  48. ## Unemployment in the United States
  49. ##################################################################

  50. unemployUSA <- read.csv('data/unemployUSA.csv')
  51. nms <- unemployUSA$Series.ID
  52. ##columns of annual summaries
  53. annualCols <- 14 + 13*(0:12)
  54. ## Transpose. Remove annual summaries
  55. unemployUSA <- as.data.frame(t(unemployUSA[,-c(1, annualCols)]))
  56. ## First 7 characters can be suppressed
  57. names(unemployUSA) <- substring(nms, 7)
  58. head(unemployUSA)

  59. library(zoo)

  60. Sys.setlocale("LC_TIME", 'C')
  61. idx <- as.yearmon(row.names(unemployUSA), format='%b.%Y')
  62. unemployUSA <- zoo(unemployUSA, idx)

  63. isNA <- apply(is.na(unemployUSA), 1, any)
  64. unemployUSA <- unemployUSA[!isNA,]

  65. save(unemployUSA, file='data/unemployUSA.RData')

  66. ##################################################################
  67. ## Gross National Income and $CO_2$ emissions
  68. ##################################################################

  69. library(WDI)
  70.   
  71. CO2data <- WDI(indicator=c('EN.ATM.CO2E.PC', 'EN.ATM.CO2E.PP.GD',
  72.               'NY.GNP.MKTP.PP.CD', 'NY.GNP.PCAP.PP.CD'),
  73.           start=2000, end=2011,
  74.           country=c('BR', 'CN', 'DE', 'ES',
  75.               'FI', 'FR', 'GR', 'IN', 'NO', 'US'))

  76. names(CO2data) <- c('iso2c', 'Country.Name', 'Year',
  77.                     'CO2.capita', 'CO2.PPP',
  78.                     'GNI.PPP', 'GNI.capita')

  79. isNA <- apply(is.na(CO2data), 1, any)
  80. CO2data <- CO2data[!isNA, ]

  81. CO2data$Country.Name <- factor(CO2data$Country.Name)

  82. save(CO2data, file='data/CO2.RData')
复制代码


地板
tmdxyz 发表于 2014-11-21 05:24:38
谢谢楼主的介绍。

7
lonestone 在职认证  发表于 2014-11-21 06:04:00 来自手机
ReneeBK 发表于 2014-11-21 04:08
Displaying Time Series, Spatial, and Space-Time Data with R
https://github.com/oscarperpinan/spac ...
лл

8
yhw1234 学生认证  发表于 2014-11-29 12:10:34
楼主,怎么只有数据和代码,怎么没有对应的PDF书籍Displaying time series, spatial and space-time data with R?

9
YONGHU33 发表于 2015-4-28 08:23:12
楼主发的两本都是只有代码没有书,要是有书就好了

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
扫码
拉您进交流群
GMT+8, 2026-1-16 23:56