R dataframe创建一对一关系

时间:2017-09-14 01:15:51

标签: r dataframe relationship

专家,在下面的R数据框架中寻找一些建议我需要为特定城市内的每个区域建立关系。

输入:

mydf = data.frame(City = c("LA", "LA", "LA", "NYC", "NYC"), 
           Zone = c("A1", "A2", "A3", "B1", "B2"))

enter image description here

预期输出:

Output

2 个答案:

答案 0 :(得分:0)

这几乎肯定不是最有效的做事方式,但它会起作用并且几乎可读。

library(tidyverse)
library(magrittr)

output <- mydf %>%
  split(., f=mydf[, "City"]) %>%                   # Split into data.frames by "City"
  sapply(., function(x) use_series(x, Zone)) %>%   # Extract zones
  sapply(combn, 2) %>%                             # Find all combinations of size 2
  do.call("cbind", .) %>%                          # Combine them into a data frame
  t %>%
  as.data.frame %>%
  rbind(., data.frame(V1=.$V2, V2=.$V1))           # Add it to the inverse, to get all possible combinations

colnames(output) <- c("Zone_1", "Zone_2")          # Rename columns



output
      Zone_1 Zone_2
1     A1     A2
2     A1     A3
3     A2     A3
4     B1     B2
5     A2     A1
6     A3     A1
7     A3     A2
8     B2     B1

答案 1 :(得分:0)

这是一种定义组合功能的整合方法。适用于每个城市的区域:

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 all 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 is no longer needed
mydf <- mydf %>% select(-City)

数据:

mydf = data.frame(City = c("LA", "LA", "LA", "NYC", "NYC"), 
                  Zone = c("A1", "A2", "A3", "B1", "B2"),
                  stringsAsFactors = F)