0

I have two dataframes, both of them have three columns, name, latitude and longitude. I want to find the distances between them. I wrote a function called distance with four parameters (lat1, long1, lat2, long2). That is working well. I want to append everything into a dataframe. I wrote the following function,

map <- function (p,k){
  for(i in 1:nrow(p)){
    q = 0
    data = data.frame(w= numeric(0), e = numeric(0), z =  character(0))
    for(j in 1:nrow(k)){
      data$e[q] = p$name[i]
      data$z[q] = k$cellname[j]
      data$w[q] = earthDist(p$lon[i],p$lat[i], k$longitude[j], k$latitude[j]) / 1.6
      q =q + 1
    }
  }

}

But this is throwing error,

" replacement has 1 row, data has 0 "

and warning,

"invalid factor level, NA generated".

I want to create a dataframe such as,

Data1     Data2      Distance
A1          A2          2.0
A1          B2          3.5
A1          C2          5.0
.
.
.
.

Can anybody help me in creating such a dataframe or tell what is the mistake here.

Thanks

Observer
  • 641
  • 2
  • 14
  • 31
  • Why not use [this](http://stackoverflow.com/questions/35743397/calculate-distance-between-2-lat-longs#35743674) way. Besides that, please read (1) [how do I ask a good question](http://stackoverflow.com/help/how-to-ask), (2) [How to create a MCVE](http://stackoverflow.com/help/mcve) as well as (3) [how to provide a minimal reproducible example in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#answer-5963610). Then edit and improve your question accordingly. I.e., provide input data posting e.g. the result of `dput(mydata)`. – lukeA Apr 26 '16 at 20:57
  • @lukeA I have already created the function for calculating distance. Just not able to figure out how to append it to a dataframe. Regarding the question, I apologize for it. Will try to change it – Observer Apr 26 '16 at 21:04
  • There are several mistakes in the code. q should probably start at 1 and not 0. data$e should be character and not numeric. use data as the last statement in the function or since this function will return q. Try these corrections and attach some sample data to additional assistance. – Dave2e Apr 26 '16 at 22:27

0 Answers0