汇总R数据帧中的列,而与顺序无关(df $ A,df $ B)=(df $ B,df $ A)

时间:2018-07-10 21:36:09

标签: r dataframe merge summarization

我有以下数据框:


    
      destiny origin Count
    1 KJFK    SBBR       4
    2 KJFK    SAEZ    4683
    3 SBGL    KJFK       2
    4 SBBR    KJFK       2
    5 KJFK    SBGL    4987
    6 KJFK    SBGR   12911
    ...
    

在这条路线上我很有趣,对我而言,KJFK-> SBBR与SBBR-> KJFK相同。所以我想总结一下它们的数量,如下表


    
      destiny origin Count
    1 KJFK    SBBR       6
    2 KJFK    SAEZ    4683
    3 SBGL    KJFK    4989
    4 KJFK    SBGR   12911
    ...
    

我不想使用一个大的for循环来评估所有值

2 个答案:

答案 0 :(得分:1)

怎么样?

library(tidyverse)
df %>%
    mutate_if(is.factor, as.character) %>%
    rowwise() %>%
    mutate(grp = paste0(sort(c(destiny, origin)), collapse = "_")) %>%
    ungroup() %>%
    group_by(grp) %>%
    summarise(Count = sum(Count)) %>%
    separate(grp, into = c("destiny", "origin"))
#        # A tibble: 4 x 3
#  destiny origin Count
#  <chr>   <chr>  <int>
#1 KJFK    SAEZ    4683
#2 KJFK    SBBR       6
#3 KJFK    SBGL    4989
#4 KJFK    SBGR   12911

请注意,由于您不关心destinyorigin的顺序,因此在这里我们按字母顺序对其进行排序。因此,在您上面给出的示例中,KJFK -> SBBRSBBR -> KJFK将变为destiny = KJFK, origin = SBBR


样本数据

df <- read.table(text =
    "  destiny origin Count
    1 KJFK    SBBR       4
    2 KJFK    SAEZ    4683
    3 SBGL    KJFK       2
    4 SBBR    KJFK       2
    5 KJFK    SBGL    4987
    6 KJFK    SBGR   12911", header =T)

答案 1 :(得分:1)

这里是pmin/pmax

的一个选项
library(tidyverse)
df1 %>%       
  group_by(destinyN = pmin(destiny, origin), originN = pmax(destiny, origin)) %>% 
  summarise(destiny = first(destiny), 
            origin = first(origin), 
            Count = sum(Count)) %>%
  ungroup %>%
  select(-destinyN, -originN)
# A tibble: 4 x 3
#  destiny origin Count
#  <chr>   <chr>  <int>
#1 KJFK    SAEZ    4683
#2 KJFK    SBBR       6
#3 SBGL    KJFK    4989
#4 KJFK    SBGR   12911

数据

df1 <- structure(list(destiny = c("KJFK", "KJFK", "SBGL", "SBBR", "KJFK", 
"KJFK"), origin = c("SBBR", "SAEZ", "KJFK", "KJFK", "SBGL", "SBGR"
), Count = c(4L, 4683L, 2L, 2L, 4987L, 12911L)), .Names = c("destiny", 
"origin", "Count"), row.names = c("1", "2", "3", "4", "5", "6"
), class = "data.frame")