Search code examples
rmappinggeo

mapping train data to meta data


I want to convert meta data mapping train data. Because longitude and latitude is not worth for my train data. So i will use mean of distance of meta data. I've tried merge function but it's no good.

Example :

1) train data

station  log  lat
      A  123  127
      B  121  126
      C  127  129
      D  113  118
      E  119  118

2) meta data

from  to
   A   C
   B   C
   A   D
   A   E
   D   E

3) Desired Output

from fromlog fromlat tolog tolat
   A     123     127   127   129
   B     121     126   127   129
   A     123     127   113   118
   A     123     127   119   118
   D     113     118   119   118

Solution

  • In base R, we can use match, inside a lapply call

    do.call(cbind.data.frame, unlist(lapply(df2, function(x) {
         inds <- match(x, df1$station)
         list(log = df1$log[inds], lat = df1$lat[inds])
    }), recursive = FALSE))
    
    #  from.log from.lat to.log to.lat
    #1      123      127    127    129
    #2      121      126    127    129
    #3      123      127    113    118
    #4      123      127    119    118
    #5      113      118    119    118
    

    data

    df1 <- structure(list(station = c("A", "B", "C", "D", "E"), log = c(123L, 
    121L, 127L, 113L, 119L), lat = c(127L, 126L, 129L, 118L, 118L
    )), row.names = c(NA, -5L), class = "data.frame")
    
    df2 <- structure(list(from = c("A", "B", "A", "A", "D"), to = c("C", 
    "C", "D", "E", "E")), row.names = c(NA, -5L), class = "data.frame")