R dataframe create One to One Relationship -


experts, looking advice below r dataframe need build relationship each zone's within particular city.

input:

mydf = data.frame(city = c("la", "la", "la", "nyc", "nyc"),             zone = c("a1", "a2", "a3", "b1", "b2")) 

enter image description here

expected output:

output

here's tidyverse approach defines function combinations & applies each city's zones:

library(dplyr); library(tidyr); library(purrr)  generate_combinations <- function(data){   zone <- data %>% select(zone) %>% unlist()   combinations <- expand.grid(zone_1 = zone, zone_2 = zone) # generate combinations   combinations <- combinations %>%      filter(!(zone_1 == zone_2)) %>% # remove invalid combinations     mutate_all(as.character)   return(combinations) }  mydf <- mydf %>%    nest(zone) %>%   mutate(data = map(data, generate_combinations)) %>%   unnest()  > mydf    city zone_1 zone_2 1   la     a2     a1 2   la     a3     a1 3   la     a1     a2 4   la     a3     a2 5   la     a1     a3 6   la     a2     a3 7  nyc     b2     b1 8  nyc     b1     b2  # if city info no longer needed mydf <- mydf %>% select(-city) 

data:

mydf = data.frame(city = c("la", "la", "la", "nyc", "nyc"),                    zone = c("a1", "a2", "a3", "b1", "b2"),                   stringsasfactors = f) 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -