aggregate in R by permutations of column values

后端 未结 1 1776
梦如初夏
梦如初夏 2021-01-26 06:41

Background: I\'m working with origin-destination data. I would like to calculate the proportional flow between each pair of cities. However, I\'m finding it dif

相关标签:
1条回答
  • 2021-01-26 07:24

    Here is one solution:

    library(dplyr)
    df$pair <- ifelse(df$Destination < df$Origin,
                      paste(df$Destination, df$Origin, sep = ','),
                      paste(df$Origin, df$Destination, sep = ','))
    
    df %>% group_by(pair) %>% summarise(Flow = paste(Flow, collapse = ' + '))
    
    Source: local data frame [2 x 2]
    
       pair    Flow
      (chr)   (chr)
    1   a,b f1 + f2
    2   c,d f3 + f4
    

    The Flow column is obviously paste using character vectors since that is what you gave. You can modify to sum(Flow) if you have numeric values.

    EDITED: Sorry, earlier, I was summing wrong column. Fixed.

    0 讨论(0)
提交回复
热议问题