1
$\begingroup$

I have a data frame with latitude and longitude of a particular place. one place can have multiple lat, longs and those lat, long values can be same or different. I need to find the correct lat, long based on no.of occurances of lat, long for particular place.

example input data frame

df:

place    lat      long
hsy      7.343    32.849
hsy      7.343    32.122
hsy      7.567    31.567
hsy      6.934    32.122
bls      2.67     6.2
bls      3.345    5.9
bls      2.987    6.321
bls      2.987    4.56
bls      1.876    6.321
bls      2.987    6.321

expected output data frame

    place    lat      long
    hsy      7.343    32.122
    bls      2.987    6.321

expected output for lat is which ever value is occurred more times among its values for particular place and the output for 'long' column value also which ever value is occurred more times among its values for particular place.

tried below code using across, but across is not working. getting Error: 'across' is not an exported object from 'namespace:dplyr' or could not find function "across" error. any alternative for across function?

df %>%
  group_by(place) %>%
  summarise(across(c(lat, long),~names(sort(table(.x), decreasing = TRUE))[1]))
$\endgroup$
2
  • $\begingroup$ what should happen if there is a tie in the number of times two or more values occur? $\endgroup$
    – atiretoo
    Mar 18, 2021 at 19:10
  • $\begingroup$ we can take any one value from those tied values $\endgroup$
    – user113520
    Mar 19, 2021 at 13:56

1 Answer 1

0
$\begingroup$

I think below code may help you.

df <-data.frame(place=c('hsy','hsy','hsy','hsy','bls','bls','bls','bls','bls','bls'),
                lat = c(7.343,7.343,7.567,6.934,2.67,3.345,2.987,2.987,1.876,2.987),
                long=c(32.849,32.122,31.567,32.122,6.2,5.9,6.321,4.56,6.321,6.321) )

library(dplyr)

Mode function which will fetch number which has highest frequency

mode_fun<-function(x){
  tbl=table(x)
  tbl=sort(tbl,decreasing = T)
  return(as.numeric(names(tbl[1])))
}

df1  = df %>% group_by(place) %>% summarise(lat1=mode_fun(lat),long1=mode_fun(long))
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.