hey how can i assign or match the value of one data frame with nearest value(equal values are not available) in other data frame?
A=data.frame(lat=runif(10,29,34),
long=runif(10,69,72))
B=data.frame(lat=runif(10,29,34),
long=runif(10,69,72))
hey how can i assign or match the value of one data frame with nearest value(equal values are not available) in other data frame?
A=data.frame(lat=runif(10,29,34),
long=runif(10,69,72))
B=data.frame(lat=runif(10,29,34),
long=runif(10,69,72))
In terms of an algorithmic approach you would...
1)Match the values from one frame to all the values of the second frame
2)calculate a distance metric between pairs of values. Probably absolute distance.
3)group by the first set of values (the ones you are matching to) apply a per group ordering over the distance metric, so that the value closest to zero is the first value.
4) take the first pair in each group
how you can write code for that ? i am unable to construct the code
library(tidyverse)
df1 <- data.frame(
entry=1:10,
lat1=runif(10,29,34))
df2 <- data.frame(
entry2=1:10,
lat2=runif(10,29,34))
step1 <- expand_grid(df1, df2)
step2 <- mutate(step1, distance_metric = abs(lat1 - lat2))
step3 <- arrange(step2, entry, distance_metric)
step4 <- group_by(step3, entry) %>% slice(1)
step5 <- ungroup(step4) %>% select(lat1, lat2)
its expand_grid or expand.grid?
why its giving error
library(tidyverse)
library(dplyr)
df1 <- data.frame(
entry=1:10,
lat1=runif(10,29,34))
df2 <- data.frame(
entry2=1:10,
lat2=runif(10,29,34))
step1 <- expand_grid(df1, df2)
#> Error in expand_grid(df1, df2): could not find function "expand_grid"
step2 <- mutate(step1, distance_metric = abs(lat1 - lat2))
#> Error in mutate(step1, distance_metric = abs(lat1 - lat2)): object 'step1' not found
step3 <- arrange(step2, entry, distance_metric)
#> Error in arrange(step2, entry, distance_metric): object 'step2' not found
step4 <- group_by(step3, entry) %>% slice(1)
#> Error in group_by(step3, entry): object 'step3' not found
step5 <- ungroup(step4) %>% select(lat1, lat2)
#> Error in ungroup(step4): object 'step4' not found
Created on 2020-02-09 by the reprex package (v0.3.0)
It's in tidyr which I think is in tidyverse.
Try
packageVersion("tidyr")
You'd want 0.83 or higher for that function