2017-09-14 92 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