R Message: Error - replacement has x rows, data ha

2019-05-28 10:02发布

问题:

I am trying to use the package ggmap to caculate the distance for a target address with a list of addresse. My data in a csv looks like below:

Order ID    Address
1652049  435 E 70TH ST,10021
1652123  1365 YORK AVE,10021
1652053  530 E 72ND ST,10021

so I try to get the distance from my input address to all those address for example: 400 Hudson St,10013, and I have following code in R:

library(ggmap)
mydata<-read.csv("address.csv")
mydata$Address<-as.character(mydata$Address)
mydata$Distance<-NA
a<-c("289 Hudson St,10013")
mydata$Distance<-mapdist(mydata$Address,a)$miles

However the code gives me a error message as below:

Error in `$<-.data.frame`(`*tmp*`, "Distance", value = c(8.2403854, 8.2403854,  : 
  replacement has 53 rows, data has 31

回答1:

Make sure column names don't have spaces; so instead of the name "Order ID", use something like "Order_ID". Also have each address as its own separate string:

library(ggmap)

mydata$Address<-as.character(mydata$Address)
mydata$Distance<-NA
a<-c("289 Hudson St,10013")
mydata$Distance<-mapdist(mydata$Address,a)$miles

Output:

  Order_ID             Address Distance
1  1652049 435 E 70TH ST,10021 8.240385
2  1652123 1365 YORK AVE,10021 8.475275
3  1652053 530 E 72ND ST,10021 8.618197

Sample data:

mydata <- data.frame(Order_ID=c(1652049,1652123,1652053),
                     Address=c('435 E 70TH ST,10021','1365 YORK AVE,10021',
                               '530 E 72ND ST,10021'))

EDIT:

Note that in the above data, each address is its own string within a vector c(). We can see this is the case by the use of single quotation marks around each address. The reason we do this is to prevent mixing up the data in the case of using CSV files, which have columns that are comma-separated. Before reading a CSV file into R which has commas in its columns, like the address column above, make sure each value/cell in that column is saved as its own string as I've done (i.e. surrounded by single quotes).



标签: r spatial ggmap