2017-10-17 59 views
0

我写了以下函数来计算两个位置之间的移动距离。矢量的叉积

# Get Distance 
require(RJSONIO) 
address1 = "Noida Sector 62" 
address2 = "Connaught Place" 
url <- "https://maps.googleapis.com/maps/api/distancematrix/json?" 
url <- URLencode(paste(url, "origins=", address1,"&", "destinations=", address2, "&sensor=false", "&units=metric", "&mode=driving", sep = "")) 
x <- fromJSON(url, simplify = FALSE) 
metres = x$rows[[1]]$elements[[1]]$distance$text 

我想作出上述程序运行在下面的载体中提到的地点的所有可能的组合 -

address = c("Noida Sector 62" , "Saket", "Delhi University, North Campus", "Laxmi Nagar", "Khan Market", "Connaught Place") 
+0

'address1'是否可以等于'address2'? – PoGibas

+0

你可以看看'?combn'或者(如果你想考虑address1 == address2)''outer''。 – Frank

+0

不,它不能相同 – john

回答

1

这是一个解决方案,使用expand.grid来获得所有地址组合。

distance <- function(a1, a2){ 
    url <- "https://maps.googleapis.com/maps/api/distancematrix/json?" 
    url <- URLencode(paste(url, "origins=", a1,"&", "destinations=", a2, "&sensor=false", "&units=metric", "&mode=driving", sep = "")) 
    x <- fromJSON(url, simplify = FALSE) 
    metres <- x$rows[[1]]$elements[[1]]$distance$text 
    metres 
} 

address = c("Noida Sector 62" , "Saket", "Delhi University, North Campus", "Laxmi Nagar", "Khan Market", "Connaught Place") 

add <- expand.grid(A1 = address, A2 = address, stringsAsFactors = FALSE) 
add <- add[add$A1 != add$A2, ] 
row.names(add) <- NULL 
d <- apply(add, 1, function(x) distance(x[1], x[2])) 
d 
#[1] "29.0 km" "24.0 km" "10.7 km" "18.1 km" "18.3 km" "27.3 km" "27.0 km" 
# [8] "18.6 km" "11.1 km" "15.8 km" "28.2 km" "28.3 km" "15.3 km" "16.8 km" 
#[15] "8.5 km" "11.3 km" "20.2 km" "15.3 km" "8.8 km" "7.4 km" "18.8 km" 
#[22] "10.9 km" "17.7 km" "8.3 km" "5.5 km" "19.5 km" "14.0 km" "9.4 km" 
#[29] "7.1 km" "4.7 km" 
1

使用combn创建地址的所有可能的组合(这里我们使用m = 2因为我们想要两个组合)。然后使用循环遍历对(foo矩阵)。

require(RJSONIO) 
api <- "API_SEQUENCE" 

address <- c("Noida Sector 62" , "Saket", "Delhi University, North Campus", "Laxmi Nagar", "Khan Market", "Connaught Place") 

foo <- combn(address, 2) 
metres <- list() 
for(i in 1:ncol(foo)) { 
    address1 <- foo[1, i] 
    address2 <- foo[2, i] 
    url <- "https://maps.googleapis.com/maps/api/distancematrix/json?" 
    url <- URLencode(paste(url, "origins=", address1,"&", "destinations=", address2, "&sensor=false", "&units=metric", "&mode=driving", sep = "")) 
    x <- fromJSON(url, simplify = FALSE) 
    metres[[i]] <- x$rows[[1]]$elements[[1]]$distance$text 
} 

foo[, 1:5] 
    [,1]    [,2]        [,3]    
[1,] "Noida Sector 62" "Noida Sector 62"    "Noida Sector 62" 
[2,] "Saket"   "Delhi University, North Campus" "Laxmi Nagar"  
    [,4]    [,5]    
[1,] "Noida Sector 62" "Noida Sector 62" 
[2,] "Khan Market"  "Connaught Place" 
+0

为什么'foo [,i] [1]'而不是'foo [1,i]'? –

+0

url需要在for循环中,否则以前迭代的链接会被使用。也没有返回所有组合的米 – john

+0

@John改变了循环输出:它附加到每个迭代的“米”列表 – PoGibas