【问题标题】:How can I sum values in another df based on a condition in both df's in r? [duplicate]如何根据 r 中两个 df 的条件对另一个 df 中的值求和? [复制]
【发布时间】:2020-05-24 08:20:15
【问题描述】:

我对 R 很陌生,但我找不到解决问题的正确方法。

我有两个 df:一个在会话级别,一个在客户端级别。在客户端级别 df 中,我想将客户端在会话 df 中完成的会话数相加。

df 的样子:

          df1                                df2
Sessionid     Client id                    Clientid     
   1              1                           1                 
   2              1                           2                 
   3              2                  
   4              2                  
   5              2    

我想要这样的输出:

          df1                                df2
Sessionid     Client id             Clientid     Number_of_sessions
   1              1                    1                 2
   2              1                    2                 3
   3              2                  
   4              2                  
   5              2    

【问题讨论】:

    标签: r sum


    【解决方案1】:

    一种选择是使用dplyr 库:

    df %>%
      group_by(Clientid) %>%
      summarise(Number_of_sessions = n())
    
    # Clientid Number_of_sessions
    # <int>              <int>
    # 1        1           2
    # 2        2           3
    

    aggregate(Sessionid ~ Clientid, df, length)
    

    返回相同的东西。

    数据:

    structure(list(Sessionid = 1:5, Clientid = c(1L, 1L, 2L, 2L, 
    2L)), class = "data.frame", row.names = c(NA, -5L)) -> df
    

    【讨论】:

      【解决方案2】:

      你可以试试

      library(dplyr)
      count(group_by(df1, `Client id`), name = "Number_of_sessions")
      #> # A tibble: 2 x 2
      #> # Groups:   Client id [2]
      #>   `Client id` Number_of_sessions
      #>         <int>              <int>
      #> 1           1                  2
      #> 2           2                  3
      
      
      

      【讨论】:

        【解决方案3】:

        一个简单的基础 R 解决方案是

        df2 <- as.data.frame(table(df1$Clientid))
        names(df2) <- c("Clientid", "Number_of_sessions")
        

        输出

        #   Clientid Number_of_sessions
        # 1        1                  2
        # 2        2                  3
        

        【讨论】:

        • 要使其成为数据框,请使用as.data.frame(table(df$Clientid))
        • 正确,我编辑我的答案。谢谢
        猜你喜欢
        • 2019-11-02
        • 1970-01-01
        • 2012-10-12
        • 1970-01-01
        • 1970-01-01
        • 2020-09-16
        • 2020-12-29
        • 1970-01-01
        • 2020-10-24
        相关资源
        最近更新 更多