xy.coords中的R语言错误(x,y)

时间:2014-12-17 10:35:26

标签: r

我正在关注Vizualise连接R http://flowingdata.com/2011/05/11/how-to-map-connections-with-great-circles/

的教程(这是我第一次使用R)

我做了一些小改动来显示特定数据,但是在执行绘制lines()函数的最后一步时遇到了一些问题。

执行以下c

时出现以下错误
Error in xy.coords(x, y) : 
  'x' is a list, but does not have components 'x' and 'y'

我传递给情节的信息如下

> airports
    iata                                      country        lat        long
1     AD                                      Andorra  42.546245    1.601554
2     AE                         United Arab Emirates  23.424076   53.847818

>flights
  AIRLINE AIRLINE1 AIRPORT CNT
1    AK02       NZ      AR 130
2    AS01       GB      AE 257

我试图执行的代码如下

library(maps)
library(geosphere)
library(XLConnect)               # load XLConnect package 

wk1 = loadWorkbook("C:/Users/cacoteh/AppData/Local/NoBackup/flights.xlsx") 
wk2 = loadWorkbook("C:/Users/cacoteh/AppData/Local/NoBackup/airports.xlsx") 

flights = readWorksheet(wk1, sheet="flights")
airports = readWorksheet(wk2, sheet="airports")

# Unique carriers
carriers <- unique(flights[1])

# Color
pal <- colorRampPalette(c("#333333", "white", "#1292db"))
colors <- pal(100)

pdf(paste("carrier.pdf", sep=""), width=11, height=7)
map("world", col="#f2f2f2", fill=TRUE, bg="#f5f5dc", lwd=0.05)
maxcnt <- max(flights["CNT"])
for (j in 1:nrow(flights) ) {
  air1 <- flights[j,"AIRLINE1"]
  for (k in 1: nrow(airports) ) { 
    if ( airports[k,1] == air1 ) {
      lat1 <- airports[k,3]
      lon1 <- airports[k,4]
    }
  }
  air2 <- flights[j,"AIRPORT"]
  for (k in 1: nrow(airports) ) { 
    if ( airports[k,1] == air2 ) {
      lat2 <- airports[k,3]
      lon2 <- airports[k,4]
    }
  }

  inter <- gcIntermediate(c(lon1, lat1), c(lon2, lat2), n=100, addStartEnd=TRUE, breakAtDateLine=TRUE)
  colindex <- round( ( flights[j,4] / maxcnt )* length(colors) )
  lines(inter, col="black", lwd=0.8)
    }

dev.off()

gcIntermediate(inter)的输出如下:

> inter
[[1]]
          lon       lat
[1,] 174.8860 -40.90056
[2,] 175.6352 -41.51760
[3,] 176.3988 -42.12968
[4,] 177.1773 -42.73661
[5,] 177.9710 -43.33816
[6,] 178.7806 -43.93411
[7,] 180.0000 -44.52423

[[2]]
             lon       lat
 [1,] -180.00000 -45.10827
 [2,] -178.69075 -45.68599
 [3,] -177.81287 -46.25713
 [4,] -176.91662 -46.82140

不确定错误到底在哪里。如果有人能够给我一个帮助,我会很感激。

谢谢你, 雨果

1 个答案:

答案 0 :(得分:1)

#lines(inter,col="#bb4cd4",lwd=1) only for the result is matrix but not list
#so you can do it like this:
if(is.matrix(inter))
lines(inter,col="#bb4cd4",lwd=1)
else {
lines(inter[[1]],col="#bb4cd4",lwd=1);
lines(inter[[2]],col="#bb4cd4",lwd=1)
}