Grouping edges to create an undirected set.

Hello,

So I have the following dataframe:

From_test <- c("crayon", "crayon", "crayon", "crayon", "crayon", "crayon", "crayon", "broom", "Cairo", "caret", "carData", "caTools", "cellranger", "checkmate")
To_test <- c("broom", "BSDA", "callr", "car", "caret", "Ensemble", "caTools", "crayon", "crayon", "crayon", "crayon", "crayon", "crayon", "crayon")
Value_test <- c("69", "1", "4", "11", "1", "1", "3", "19", "1", "3", "1", "1", "58", "1")

df_test <- cbind(From_test,To_test,Value_test)

I want the list to be reduced further by an additional group by. Essentially, the from and to needs to sum up where the from to matches a to from combination of the same combination of names.

So: crayon broom of 69 should be added to broom crayon of 19 and the final output should be crayon broom with a value of 88.

Are you looking for something like this?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df_test <- data.frame(From_test = c("crayon", "crayon", "crayon", "crayon", "crayon", "crayon", "crayon", "broom", "Cairo", "caret", "carData", "caTools", "cellranger", "checkmate"),
                      To_test = c("broom", "BSDA", "callr", "car", "caret", "Ensemble", "caTools", "crayon", "crayon", "crayon", "crayon", "crayon", "crayon", "crayon"),
                      Value_test = c(69, 1, 4, 11, 1, 1, 3, 19, 1, 3, 1, 1, 58, 1),
                      stringsAsFactors = FALSE)

df_test %>%
  rowwise() %>%
  mutate(temp = paste(sort(x = c(From_test, To_test)),
                      collapse = " ")) %>%
  ungroup() %>%
  group_by(temp) %>%
  mutate(result = sum(Value_test)) %>%
  ungroup() %>%
  select(-temp)
#> # A tibble: 14 x 4
#>    From_test  To_test  Value_test result
#>    <chr>      <chr>         <dbl>  <dbl>
#>  1 crayon     broom            69     88
#>  2 crayon     BSDA              1      1
#>  3 crayon     callr             4      4
#>  4 crayon     car              11     11
#>  5 crayon     caret             1      4
#>  6 crayon     Ensemble          1      1
#>  7 crayon     caTools           3      4
#>  8 broom      crayon           19     88
#>  9 Cairo      crayon            1      1
#> 10 caret      crayon            3      4
#> 11 carData    crayon            1      1
#> 12 caTools    crayon            1      4
#> 13 cellranger crayon           58     58
#> 14 checkmate  crayon            1      1

Created on 2019-04-02 by the reprex package (v0.2.1)

2 Likes

This is perfect! Thanks so much :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.