2017-09-14 121 views
0

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

输入:

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

enter image description here

预期输出:

Output

+0

是否存在的第2行中的错字输出表? (A1,A2)重复两次。应该是(A1,A3)而不是? –

+0

是的,你是对的。它应该是(A1,A3) – Kg211

+0

你几乎可以通过使用'melt(crossprod(table(mydf)))'到达那里,但为了得到预期的结果,你可以使用'temp < - crossprod(table(mydf)); diag(temp)< - NA; r < - reshape2 :: melt(temp,na.rm = TRUE); r [r $ value == 1,]' – user20650

回答

0

下面是定义组合&功能的tidyverse方法适用于每个城市的区域:

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) 
+0

完美。谢谢!! – Kg211

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 
+0

完美。如预期。谢谢!! – Kg211